在golang中使用template.ParseFiles的多个文件
例如,去吧,我有在golang中使用template.ParseFiles的多个文件,go,go-templates,Go,Go Templates,例如,去吧,我有 package main import "html/template" import "net/http" func handler(w http.ResponseWriter, r *http.Request) { t, _ := template.ParseFiles("header.html", "footer.html") t.Execute(w, map[string] string {"Title": "My title", "Body": "H
package main
import "html/template"
import "net/http"
func handler(w http.ResponseWriter, r *http.Request) {
t, _ := template.ParseFiles("header.html", "footer.html")
t.Execute(w, map[string] string {"Title": "My title", "Body": "Hi this is my body"})
}
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":8080", nil)
}
在header.html中:
Title is {{.Title}}
Title is {{.Title}}
{{template "footer" .}}
在footer.html中:
Body is {{.Body}}
{{define "footer"}}Body is {{.Body}}{{end}}
当转到http://localhost:8080/
,我只看到“Title是我的Title”,而没有看到第二个文件footer.html。如何使用template.ParseFiles加载多个文件?最有效的方法是什么
提前感谢。只有第一个文件用作主模板。其他模板文件需要从第一个开始包括,如下所示:
Title is {{.Title}}
{{template "footer.html" .}}
“footer.html”
后的点将数据从执行
传递到页脚模板——传递的值在包含的模板中变成
。user634175的方法有一个小缺点:第一个模板中的{template“footer.html”。}
必须硬编码,这使得很难将footer.html更改为另一个页脚
这里有一点改进
header.html:
Title is {{.Title}}
Title is {{.Title}}
{{template "footer" .}}
footer.html:
Body is {{.Body}}
{{define "footer"}}Body is {{.Body}}{{end}}
因此,footer.html可以更改为定义“footer”的任何文件,以生成不同的页面这似乎正是我想要的。谢谢