在Web 應用程式中處理複雜佈局時,創建一個基本模板作為其他模板的基礎通常很有用。頁。在 Go 的 html/template 套件中,這可以使用 {{define}} 和 {{template}} 指令來實現。
考慮以下範例,其中您有一個基本佈局檔案 (base.html):
header... {{template "content" .}} footer...
以及使用自己的自訂內容重複使用此基本佈局的單獨頁面(page1.html 和 page2.html):
{{define "content"}}{{end}} {{template "base.html"}}Page1
{{define "content"}}{{end}} {{template "base.html"}}Page2
您遇到的問題是頁面 1 和頁面 2 使用相同的 HTML 進行渲染,該 HTML 在 page2.html 中定義。為了解決這個問題,我們需要確保兩個頁面在 {{template}} 區塊中聲明並使用自己獨特的內容部分。
更好的方法是在單獨的文件中定義模板內容,如下所示下面:
base.html:
{{define "base"}} header... {{template "content" .}} footer... {{end}}
page1.html:
{{define "content"}} I'm page 1 {{end}}
page2.html:
{{define "content"}} I'm page 2 {{end}}
在您的應用程式中,您可以使用 template.New() 和 ParseFiles() 將內容和基本模板檔案解析為模板物件。隨後,您可以透過使用ExecuteTemplate().
tmpl, err := template.New("").ParseFiles("page1.html", "base.html") // check your err err = tmpl.ExecuteTemplate(w, "base", yourContext)
免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3