htmlrustirontera

Why does Iron render my templated HTML as text?


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?


Solution

  • 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)))
    }