Golang索引模板包括

时间:2015-12-03 06:42:24

标签: templates go go-templates

我在my project中有两个模板,如下所示:

var indextemplate = template.Must(template.New("").Parse(`<!DOCTYPE html>
<form action="/compare" method="post">
<input type="date" name="from" required>
<input type="submit">
</form>`))

var comparetemplate = template.Must(template.New("").Parse("Hours since {{.From}} are {{.Duration}}"))

我不明白如何构建代码,因此我有HTML模板(最后有一个头部和</html>),只是将这些模板包含在正文中。

我也不太了解构造代码的最佳做法是什么,以便模板与处理程序匹配。从IIUC开始,您需要在处理程序之外最好地编译模板。

1 个答案:

答案 0 :(得分:3)

您应该知道的是template.Template的值可以是多个模板的集合,请参阅返回此集合的Template.Templates()方法。

集合中的每个模板都有一个可以引用的唯一名称(参见Template.Name())。并且有一个{{template "name" pipeline}}操作,使用它可以在模板中包含其他模板,另一个模板是集合的一部分。

请参阅此示例。让我们定义2个模板:

const tmain = `<html><body>
Some body. Now include the other template:
{{template "content" .}}
</body></html>
`
const tcontent = `I'M THE CONTENT, param passed is: {{.Param}}`

如您所见,tmain包含另一个名为"content"的模板。您可以使用Template.New()方法(强调:方法,不要与func template.New()混淆)来创建一个新的关联命名模板,该模板将成为模板的一部分你打电话的方法。结果,它们可以相互引用,例如,他们可以互相包容。

让我们看一下将这2个模板解析为一个template.Template的代码,以便它们可以相互引用(为简洁起见,省略了错误检查):

t := template.Must(template.New("main").Parse(tmain))
t.New("content").Parse(tcontent)

param := struct{ Param string }{"paramvalue"}

if err := t.ExecuteTemplate(os.Stdout, "main", param); err != nil {
    fmt.Println(err)
}

输出(在Go Playground上尝试):

<html><body>
Some body. Now include the other template:
I'M THE CONTENT, param passed is: paramvalue
</body></html>

替代

另请注意,如果您有许多更大的模板,那么它的可读性和可维护性就会降低。您应该考虑将模板保存为文件,并且可以使用template.ParseFiles()template.ParseGlob(),它们可以同时解析多个文件并从中构建模板集合,因此它们可以相互引用。模板的名称将是文件的名称。