使用起来完全没问题show()
。以下是它的实现方式Rocket
:
pub fn show<S, C>(rocket: &Rocket, name: S, context: C) -> Option<String>
where S: Into<Cow<'static, str>>, C: Serialize
{
let ctxt = rocket.state::<ContextManager>().map(ContextManager::context).or_else(|| {
// N.B.: removed some logging for brevity
None
})?;
Template::render(name, context).finalize(&ctxt).ok().map(|v| v.0)
}
正如你所看到的show()
,确实在内部调用render()
,就像 rustdoc 告诉我们的那样。但这里它也调用finalize()
. 让我们检查一下它的作用:
/// Actually render this template given a template context. This method is
/// called by the `Template` `Responder` implementation as well as
/// `Template::show()`.
好的,所以render()
并没有真正渲染任何东西。它finalize()
正在做这项工作。
我们还可以检查它是如何Responder
实现的:
/// Returns a response with the Content-Type derived from the template's
/// extension and a fixed-size body containing the rendered template. If
/// rendering fails, an `Err` of `Status::InternalServerError` is returned.
impl Responder<'static> for Template {
fn respond_to(self, req: &Request) -> response::Result<'static> {
let ctxt = req.guard::<State<ContextManager>>().succeeded().ok_or_else(|| {
// N.B.: removed some logging for brevity
Status::InternalServerError
})?.inner().context();
let (render, content_type) = self.finalize(&ctxt)?;
Content(content_type, render).respond_to(req)
}
}
TL;DR:似乎文档具有误导性。show()
当您调用和发送响应时,模板实现完全一样。在这两种情况下,它都会在内部调用finalize()
,从而生成String
模板的呈现。因此,使用不应该有任何性能损失show()
PS:当前main
分支的代码有点变化,但逻辑还是一样的