我有三个这样的模板:
基础.html:
<h1>Base.html rendered here</h1>
{{template "content" .}}
view.html:
{{define "content"}}
...
{{end}}
编辑.html:
{{define "content"}}
...
{{end}}
我将它们存储在"template"文件夹中。
我想要的是动态更改将在 {{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() 只接收一个字符串作为模板名称。在这种情况下,我如何渲染两个或更多模板?
最佳答案
不是在调用 ExecuteTemplate
时直接写入 http.ResponseWriter
,而是写入一个字节缓冲区,并通过准备调用将其发送到下一个模板使用 template.HTML
调用。
var b bytes.Buffer
var templates = template.Must(template.ParseGlob("templates/*.html"))
err := templates.ExecuteTemplate(b, templ_1, p)
if err != nil { //handle err }
err := templates.ExecuteTemplate(w, templ_2, template.HTML(b.String()))
if err != nil { //handle err }
如果您打算使用未知数量的模板,您可以使用字符串捕获中间步骤:
var strtmp string
err := templates.ExecuteTemplate(b, templ_1, p)
if err != nil { //handle err }
strtemp = b.String() //store the output
b.Reset() //prep buffer for next template's output
err := templates.ExecuteTemplate(b, templ_2, template.HTML(strtmp))
if err != nil { //handle err }
//... until all templates are applied
b.WriteTo(w) //Send the final output to the ResponseWriter
编辑:正如@Zhuharev 所指出的,如果 View 和编辑模板的组成是固定的,那么它们都可以引用 base 而不是试图提供对 View 或编辑的引用的 base:
{{define "viewContent"}}
{{template "templates/base.html" .}}
...Current view.html template...
{{end}}
{{define "editContent"}}
{{template "templates/base.html" .}}
...Current edit.html template...
{{end}}
关于go - 将一个模板渲染到另一个模板中,而无需每次都解析它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32503247/