亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

將一個模板渲染到另一個模板中,而無需每次都解析它們

將一個模板渲染到另一個模板中,而無需每次都解析它們

Go
一只斗牛犬 2021-11-08 14:37:52
我有三個這樣的模板:基地.html:<h1>Base.html rendered here</h1>{{template "content" .}}視圖.html:{{define "content"}}...{{end}}編輯.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() 只接收一個字符串作為模板的名稱。在這種情況下,我如何渲染兩個或更多模板?
查看完整描述

1 回答

?
翻過高山走不出你

TA貢獻1875條經驗 獲得超3個贊

不是http.ResponseWriter在調用 時直接寫入 ,而是寫入ExecuteTemplate字節緩沖區,然后通過調用準備調用將其發送到下一個模板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 指出的,如果視圖和編輯模板的組成是固定的,它們都可以引用 base 而不是 base 試圖提供對視圖或編輯的引用:


{{define "viewContent"}}

{{template "templates/base.html" .}}

...Current view.html template...

{{end}}


{{define "editContent"}}

{{template "templates/base.html" .}}

...Current edit.html template...

{{end}}


查看完整回答
反對 回復 2021-11-08
  • 1 回答
  • 0 關注
  • 190 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號