如何为具有公共部分的多个模型渲染模板

我的 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   

如何为具有通用页眉和页脚的指定模型呈现这些模板?


catspeake
浏览 105回答 1
1回答

森栏

只是一个准系统解决方案如下:package mainimport (    "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。
打开App,查看更多内容
随时随地看视频慕课网APP