【问题标题】:Iron renders html as textIron 将 html 渲染为文本
【发布时间】:2017-12-26 21:45:55
【问题描述】:

我的 Iron Web 应用程序的一部分:

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

它将 HTML 模板呈现为浏览器中的文本。为什么不是 HTML?

【问题讨论】:

    标签: html web rust iron


    【解决方案1】:

    那是因为您没有设置内容的 MIME 类型。
    有关如何解决此问题的完整示例,请参阅Iron's own examples

    一种可能性是:

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

    【讨论】:

    • 如何默认设置html content-type?
    • 不幸的是,据我所知,你不能。您可以将Ok(Response::with((content_type, iron::status::Ok, content))) 包装到一个仅将content 作为参数的函数中。如果这已经回答了您关于为什么您的模板没有显示为 HTML 的问题,请考虑选择我的答案作为已接受 :)
    猜你喜欢
    • 2021-01-05
    • 1970-01-01
    • 2012-10-31
    • 1970-01-01
    • 1970-01-01
    • 2017-01-29
    • 2011-06-01
    • 2011-07-12
    • 1970-01-01
    相关资源
    最近更新 更多