我是新来的Golang的世界,我试图建立一个模板文件和良好的缓存系统的Web项目。Golang多模板缓存
我有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。 (每次呈现页面时)非常糟糕PERF
- 定义模板的数组像这样在初始化函数(example):
templates["1"] = template.Must(template.ParseFiles("layout.html","1.html")) templates["2"] = template.Must(template.ParseFiles("layout.html","2.html"))
有没有什么新的方式或更好的方式来做到这一点?
解析的模板不“越权”对方,除非他们有相同的确切的文件名(但不同的路径)。它们都是分开存储的,你只需要使用文件名来执行它。 – RayfenWindspear
@RayfenWindspear,你能告诉我一个例子PLS –