【发布时间】:2021-01-13 17:52:56
【问题描述】:
要清理模板文件夹,我想将常用模板保存在子文件夹中。目前我有以下文件结构:
main.go
templates/index.tpl # Main template for the main page
templates/includes/head.tpl
templates/includes/footer.tpl
head.tpl 和 footer.tpl 将在 index.tpl 内调用,如下所示:
{{ template "head" . }}
<h1>My content</h1>
{{ template "footer" .}}
此外,使用template.ParseGlob() 解析文件。这是main.go的摘录:
var views = template.Must(template.ParseGlob("src/templates/**/*"))
func Render(rw http.ResponseWriter, temp string, data interface{}) {
err := views.ExecuteTemplate(rw, temp, data)
if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
}
}
func Index(rw http.ResponseWriter, req *http.Request) {
Render(rw, "index.tpl", nil)
}
每次打开浏览器时都会收到以下错误消息:html/template: "index.tpl" is undefined。
这种全局模式是否有可能忽略index.tpl?
我发现了this 类似的问题,但答案只是一种解决方法。
【问题讨论】: