【发布时间】:2017-08-22 22:52:13
【问题描述】:
我是 Golang 世界的新手,我正在尝试使用模板文件和良好的缓存系统建立一个 Web 项目。
我有layout.html、1.html、2.html。
所以我在我的渲染函数中加载了layout.html:
err := templates.ExecuteTemplate(w, "layout.html", nil)
layout.html 看起来像这样:
...
<body>{{template "content" .}}</body>
...
1.html
{{define "content"}}This is the first page.{{end}}
2.html
{{define "content"}}This is the second page.{{end}}
我不能用
var templates = template.Must(template.ParseFiles(
"layout.html",
"1.html",
"2.html"))
因为2.html 覆盖1.html。
所以我有两种方法:
- 在每个处理函数中定义 ParseFiles。 (每次呈现页面时)性能非常差
- 在 init 函数 (example) 中定义这样的模板数组:
templates["1"] = template.Must(template.ParseFiles("layout.html","1.html")) templates["2"] = template.Must(template.ParseFiles("layout.html","2.html"))
有什么新方法或更好的方法吗?
【问题讨论】:
-
已解析的模板不会相互“覆盖”,除非它们具有完全相同的文件名(但路径不同)。它们都单独存储,您只需使用文件名执行即可。
-
@RayfenWindspear,你能给我举个例子吗
标签: go