【问题标题】:Golang index template includingGolang 索引模板包括
【发布时间】:2016-03-07 16:16:08
【问题描述】:

我在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 模板(带有头部和末尾的 &lt;/html&gt;)并将这些模板包含到正文中。

我也不太明白构建代码以使模板与处理程序匹配的最佳实践是什么。由于 IIUC,您最好在处理程序之外编译模板。

【问题讨论】:

  • 为什么不使用模板文件?

标签: templates go go-templates


【解决方案1】:

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

【讨论】:

  • 我在github.com/kaihendry/dc/commit/… 中遇到问题,其中包含的模板没有被执行并且值被填写。所以我的输出只是 Hours since are 这是错误的。我错过了什么?
  • @hendry 那是因为您将nil 管道传递给包含的模板。如果您想传递管道(参数),请像这样包含它:{{template "content" .}} 。我编辑了答案和示例以显示通过管道。
  • 谢谢!如果github.com/kaihendry/dc RE 模板有什么更好的...请告诉我。我不喜欢单独的模板,因为它们不在二进制文件中。
猜你喜欢
  • 1970-01-01
  • 2013-03-29
  • 2010-10-25
  • 1970-01-01
  • 2017-07-19
  • 2013-06-10
  • 1970-01-01
  • 2013-08-27
相关资源
最近更新 更多