英文:
Golang index template including
问题
我在我的项目中有两个模板,如下所示:
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>
结尾)只包含这些模板的内容。
我也不太明白最佳实践是如何组织代码,以使模板与处理程序匹配。因为如果我理解正确,你需要在处理程序之外最好编译模板。
英文:
I have two templates in my project like so:
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}}"))
I don't understand how to structure the code so I have the HTML template (with a head and </html>
at the end) and just include those templates into the body.
I also don't quite understand what is best practice to structure the code so that the template matches the handler. Since IIUC you need to best compile the template outside the handler.
答案1
得分: 3
你需要知道的是,template.Template
的值可以是多个模板的集合,可以通过其 Template.Templates()
方法获取该集合。
集合中的每个模板都有一个唯一的名称,可以通过该名称进行引用(参见 Template.Name()
)。还有一个 {{template "name" pipeline}}
操作,可以在一个模板中包含其他模板,这些模板也是集合的一部分。
看看这个例子。我们定义了两个模板:
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()
方法(强调:方法,不要与 template.New()
函数混淆)创建一个新的关联命名模板,该模板将成为调用该方法的模板的一部分。因此,它们可以相互引用,例如,它们可以相互包含。
让我们看看将这两个模板解析为一个 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()
,它们都可以一次解析多个文件,并从中构建模板集合,以便它们可以相互引用。模板的名称将是文件的名称。
英文:
What you should know is that a value of template.Template
can be a collection of multiple templates, see its Template.Templates()
method which returns this collection.
Each template in the collection has a unique name that it can be referred to by (see Template.Name()
). And there is a {{template "name" pipeline}}
action, and using that you can include other templates in a template, another template which is part of the collection.
See this example. Let's define 2 templates:
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}}`
As you can see, tmain
includes another template named "content"
. You can use the Template.New()
method (stressing: method, not to be confused with the func template.New()
) to create a new associated, named template that will be part of the template whose method you're calling. As a result, they can refer to each other, e.g. they can include each other.
Let's see code that parses these 2 templates into one template.Template
so they can refer to each other (error check omitted for brevity):
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)
}
Output (try it on the Go Playground):
<html><body>
Some body. Now include the other template:
I'M THE CONTENT, param passed is: paramvalue
</body></html>
Alternative
Also note that if you have many and bigger templates, this becomes less readable and maintainable. You should consider saving your templates as files, and you can use template.ParseFiles()
and template.ParseGlob()
, both which can parse multiple files at once and they build the template collection from them, so they can refer to each other. The names of the templates will be the names of the files.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论