【发布时间】:2019-08-03 15:27:17
【问题描述】:
有没有办法让模板顺序无关紧要。
这是我的代码:
var overallTemplates = []string{
"templates/analytics.html",
"templates/header.html",
"templates/footer.html"}
func HomeHandler(w http.ResponseWriter, r *http.Request) {
render(w,
append([]string{"templates/home.html"}, overallTemplates...),
nil)
}
func render(w http.ResponseWriter, files []string, data interface{}) {
tmpl := template.Must(template.ParseFiles(files...))
err := tmpl.Execute(w, data)
if err != nil {
fmt.Printf("Couldn't load template: %v\n", err)
}
}
它有效,但如果我将overallTemplates 的顺序更改为:
var overallTemplates = []string{
"templates/header.html",
"templates/footer.html",
"templates/analytics.html"}
我得到一个空白页,因为 analytics.html 内容类似于 {{define "analytics"}}...{{end}},它由 footer.html 调用,例如 {{define "footer"}}{{template "analytics"}} ...{{end}}
【问题讨论】:
-
顺序已经或多或少无关紧要,重要的是您执行了哪个模板。
标签: go go-templates