1

A part of my Iron web application:

lazy_static! {
    pub static ref TEMPLATES: Tera = {
        let mut tera = compile_templates!("templates/**/*");
        tera.autoescape_on(vec!["html", ".sql"]);
        tera
    };
}

fn index(_: &mut Request) -> IronResult<Response> {
    let ctx = Context::new();
    Ok(Response::with((iron::status::Ok, TEMPLATES.render("home/index.html", &ctx).unwrap())))
}

It renders an HTML template as text in a browser. Why not HTML?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Posh344
  • 43
  • 1
  • 1
  • 5

1 Answers1

2

That's because you didn't set your content's MIME type.
For full examples on how to fix this, see Iron's own examples.

One possibility would be:

use iron::headers::ContentType;

fn index(_: &mut Request) -> IronResult<Response> {
    let ctx = Context::new();
    let content_type = ContentType::html().0;
    let content = TEMPLATES.render("home/index.html", &ctx).unwrap();
    Ok(Response::with((content_type, iron::status::Ok, content)))
}
Jan Hohenheim
  • 3,552
  • 2
  • 17
  • 42
  • how can I set html content-type by default? – Posh344 Jul 21 '17 at 07:43
  • 1
    You unfortunately can't, as far as I know. What you can is wrap `Ok(Response::with((content_type, iron::status::Ok, content)))` into an own function that takes only `content` as a parameter. If this has answered your question about why your template wasn't displaying as HTML, consider selecting my answer as accepted :) – Jan Hohenheim Jul 21 '17 at 09:11