【发布时间】:2014-07-28 10:30:15
【问题描述】:
我正在寻找是否有更好(更快、更有条理)的方式来拆分我在 Go 中的模板。我非常喜欢坚持使用 html/template(或其包装器),因为我信任它的安全模型。
- 现在我使用
template.ParseGlob来解析init()中的所有模板文件。 - 我将 template.Funcs 应用于生成的模板
- 我在每个模板中设置了一个
$title(即listing_payment.tmpl)并将其传递给内容模板。 - 据我了解,
html/template解析后会将模板缓存在内存中 - 我的处理程序只调用
t.ExecuteTemplate(w, "name.tmpl", map[string]interface{})并且不对每个请求进行任何愚蠢的解析。 -
我从多个部分组成模板(这是我觉得笨拙的一点),如下所示:
{{ $title := "Page Title" }} {{ template "head" $title }} {{ template "checkout" }} {{ template "top" }} {{ template "sidebar_details" . }} {{ template "sidebar_payments" }} {{ template "sidebar_bottom" }} <div class="bordered-content"> ... {{ template "listing_content" . }} ... </div> {{ template "footer"}} {{ template "bottom" }}
我的三个问题是:
这是高效的,还是多个
{{ template "name" }}标记会导致潜在的每个请求性能下降?在对较重的页面进行压力测试时,我看到很多write - broken pipe错误。这可能只是由于套接字超时(即在编写器完成之前关闭套接字)而不是某种按请求组合,但是(如果不是,请纠正我!)在 html/template 包的约束下,有没有更好的方法来做到这一点? Django's template docs 中的第一个示例接近我想要的。扩展基本布局并根据需要替换标题、侧边栏和内容块。
有点切题:当 template.ExecuteTemplate 在请求期间返回错误时,是否有惯用的方法来处理它?如果我将编写器传递给错误处理程序,我最终会在页面上看到汤(因为它只是继续写入),但重定向似乎不像惯用的 HTTP。
【问题讨论】:
标签: go