【发布时间】:2015-12-06 19:42:48
【问题描述】:
我有三个这样的模板:
base.html:
<h1>Base.html rendered here</h1>
{{template "content" .}}
view.html:
{{define "content"}}
...
{{end}}
edit.html:
{{define "content"}}
...
{{end}}
我将它们存储在文件夹“模板”中。
我想要的是动态更改将在 {{template "content" .}} 位置呈现的模板,而无需每次都解析。所以我不想要的是这个:
func main() {
http.HandleFunc("/edit", handlerEdit)
http.HandleFunc("/view", handlerView)
http.ListenAndServe(":8080", nil)
}
func handlerView(w http.ResponseWriter, req *http.Request) {
renderTemplate(w, req, "view")
}
func handlerEdit(w http.ResponseWriter, req *http.Request) {
renderTemplate(w, req, "edit")
}
func renderTemplate(w http.ResponseWriter, req *http.Request, tmpl string) {
templates, err := template.ParseFiles("templates/base.html", "templates/"+tmpl+".html")
if err != nil {
fmt.Println("Something goes wrong ", err)
return
}
someData := &Page{Title: "QWE", Body: []byte("sample body")}
templates.Execute(w, someData)
}
我正在查看 template.ParseGlobe(),以便做这样的事情
var templates = template.Must(template.ParseGlob("templates/*.html"))
... //and then somthing like this:
err := templates.ExecuteTemplate(w, tmpl+".html", p)
但是 ExecuteTamplate() 只接收一个字符串作为模板的名称。在这种情况下,我如何渲染两个或更多模板?
【问题讨论】:
-
执行模板到字符串,然后用这个字符串执行第二个模板
-
UPD:你可以在任何模板中使用
{{ template "templates/base.html" .}}
标签: go