简体   繁体   English

如何使用通用零件渲染多个模型的模板

[英]How to render templates for multiple models with common partials

I have many models in my golang project with CRUD views and I want to render these with common headers and footers but can't figure out how to do it. 我的golang项目中有很多带有CRUD视图的模型,并且我想使用通用的页眉和页脚来呈现这些模型,但无法弄清楚该如何做。 The examples I've seen are too simplistic. 我看过的例子太简单了。

Suppose I have a template structure like this: 假设我有一个这样的模板结构:

templates
  - layouts
    - header.tmpl
    - footer.tmpl
  - users
    - index.tmpl
    - new.tmpl
    - edit.tmpl
    - show.tmpl   
  - venues
    - index.tmpl
    - new.tmpl
    - edit.tmpl
    - show.tmpl   

How do I render these templates for a specified model with the common header and footer? 如何使用通用的页眉和页脚为指定模型呈现这些模板?

just a barebones solution would be the following: 只是一个准系统的解决方案如下:

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)
}

in reality you would want a function that returns a slice of the appropriate files to populate the alltmpls variable. 实际上,您需要一个函数,该函数返回适当文件的一部分以填充alltmpls变量。 It should scan your directories and get all files from there to pass to ParseFiles() and then proceed to call the Lookup and ExecuteTemplate steps for every template. 它应该扫描您的目录并从那里获取所有文件,然后传递给ParseFiles(),然后继续为每个模板调用Lookup和ExecuteTemplate步骤。

Taking this idea further, i would create a new type that would embed a template (or a slice of templates) to be annotated by a header and a footer. 进一步考虑这个想法,我将创建一个新类型,该类型将嵌入要由页眉和页脚注释的模板(或模板的一部分)。

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
}

and of course you can turn that struct embedding into a fully fledged field of []Template to do multiple ExecuteTemplates between the header and the footer. 当然,您也可以将该结构嵌入到[] Template的完整字段中,以在页眉和页脚之间执行多个ExecuteTemplate。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM