templates - Golang索引模板包括

标签 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,您最好在处理程序之外编译模板。

最佳答案

您应该知道 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() ,两者都可以一次解析多个文件,并从中构建模板集合,因此它们可以相互引用。模板的名称将是文件的名称。

关于templates - Golang索引模板包括,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34059404/

相关文章:

go - 在 helm 模板中将千兆字节转换为字节

c++ - 具有嵌套结构/类的 POD 性

c++ - 请解释这个表达

json - 在 Golang 中解码 json

go - 如何构造 time.Time 与时区偏移

json - 使用模板将 json 输出到 http.ResponseWriter

kubernetes - 为每个 namespace 定义值

c++ - 从异构模板值的容器中返回模板类型

c++ - C++ 中有没有什么方法可以在既不调用函数模板也不提供其模板参数的情况下引用函数模板?

go - redigo 是否重新连接到服务器?