在 Go 中解析多个模板

Parsing Multiple Templates in Go

我正在尝试弄清楚如何在 Go 中加载多个模板,当其中很多模板具有相似的......你可以说吗?

目前,我在正在处理的示例应用程序中加载了以下两个模板:

homeTemplate, err = template.ParseFiles(
    "views/layout/base.gohtml",
    "views/layout/menu.html",
    "views/layout/footer.gohtml",
    "views/home.gohtml")
if err != nil {
    panic(err)
}

contactTemplate, err = template.ParseFiles(
    "views/layout/base.gohtml",
    "views/layout/menu.html",
    "views/layout/footer.gohtml",
    "views/contact.gohtml")
if err != nil {
    panic(err)
}

我的问题如下:

有没有一种方法可以将每个模板列表中的前三个条目存储在一个变量中,然后只在末尾附加最后一个包含项,这样我就可以缩短编码并简化事情?

我处理这整件事是不是错了?我在某处读到过有关使用包含 template["name"] 语法的设置然后从中进行渲染的信息,也许我只需要在其余这些内容之前加载基本模板,因为它们对于布局内容来说更多或更少,并且他们可能不需要成为上述变量的一部分?

https://golang.org/pkg/html/template/#Template.Clone

Clone can be used to prepare common templates and use them with variant definitions for other templates by adding the variants after the clone is made.

baseTemplate, err = template.ParseFiles(
    "views/layout/base.gohtml",
    "views/layout/menu.html",
    "views/layout/footer.gohtml")
if err != nil {
    panic(err)
}

homeTemplate, err = template.Must(baseTemplate.Clone()).ParseFiles("views/home.gohtml")
if err != nil {
    panic(err)
}

contactTemplate, err = template.Must(baseTemplate.Clone()).ParseFiles("views/contact.gohtml")
if err != nil {
    panic(err)
}

https://play.golang.org/p/q9ox01W8U00

一种选择是使用 Template.Clone(),如您在 mkopriva 的回答中所见。请注意,Template.Clone() 不会复制模板的实际表示,克隆将与原始模板共享表示。

另一种选择是一步解析所有模板文件,因此 "base" 模板显然只会被解析一次:

all := template.Must(template.ParseFiles(
    "views/layout/base.gohtml",
    "views/layout/menu.html",
    "views/layout/footer.gohtml",
    "views/home.gohtml",
    "views/contact.gohtml",
))

并且您可以使用Template.ExecuteTemplate()来执行指定的命名模板,例如:

// To execute the home template:
err := all.ExecuteTemplate(w, "home.gohtml", params)

// To execute the contact template:
err := all.ExecuteTemplate(w, "contact.gohtml", params)

使用 Template.Clone() 的优点是您可以拥有多个同名模板,这在一次加载所有模板时不起作用。

一次加载的优点是更简单。