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

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

如何為具有公共部分的多個模型渲染模板

如何為具有公共部分的多個模型渲染模板

Go
catspeake 2023-06-05 17:03:14
我的 golang 項目中有許多帶有 CRUD 視圖的模型,我想用通用的頁眉和頁腳呈現這些模型,但不知道該怎么做。我見過的例子太簡單了。假設我有一個這樣的模板結構:templates  - layouts    - header.tmpl    - footer.tmpl  - users    - index.tmpl    - new.tmpl    - edit.tmpl    - show.tmpl     - venues    - index.tmpl    - new.tmpl    - edit.tmpl    - show.tmpl   如何為具有通用頁眉和頁腳的指定模型呈現這些模板?
查看完整描述

1 回答

?
森欄

TA貢獻1810條經驗 獲得超5個贊

只是一個準系統解決方案如下:


package main


import (

    "fmt"

    "os"

    "text/template"

)


func main() {

    //read in one go the header, footer and all your other tmpls.

    //append to that slice every time the relevant content that you want rendered.

    alltmpls := []string{"./layouts/header.tmpl", "./layouts/footer.tmpl", "./users/index.tmpl"}

    templates, err := template.ParseFiles(alltmpls...)

    t := templates.Lookup("header.tmpl")

    t.ExecuteTemplate(os.Stdout, "header", nil)

    t = templates.Lookup("index.tmpl")

    t.ExecuteTemplate(os.Stdout, "index", nil)

    t = templates.Lookup("footer.tmpl")

    t.ExecuteTemplate(os.Stdout, "footer", nil)

}

實際上,您可能需要一個返回適當文件片段的函數來填充 alltmpls 變量。它應該掃描您的目錄并從那里獲取所有文件以傳遞給 ParseFiles(),然后繼續為每個模板調用 Lookup 和 ExecuteTemplate 步驟。


進一步考慮這個想法,我將創建一個新的類型,它將嵌入一個模板(或模板的一部分),由頁眉和頁腳注釋。


type hftemplate struct {

    template.Template

    header, footer *template.Template

}


func (h *hftemplate) ExecuteTemplate(wr io.Writer, name string, data interface{}) error {

    h.header.ExecuteTemplate(wr, "header", nil)

    err := h.ExecuteTemplate(wr, name, data)

    h.footer.ExecuteTemplate(wr, "footer", nil)

    return err

}

當然,您可以將該結構嵌入到 []Template 的完全成熟的字段中,以在頁眉和頁腳之間執行多個 ExecuteTemplates。


查看完整回答
反對 回復 2023-06-05
  • 1 回答
  • 0 關注
  • 159 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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