最近,我注意到Templates()
的html/template.Template
的工作方式与text/template.Template
不同。
// go1.12
func main() {
t := template.New( "" )
println( len( t.Templates() ) )
}
此代码的结果取决于您是导入text/template
还是html/template
。你会注意到一个文本打印0而另一个打印1.由于这个,我查看了GoDoc和html的文档说Templates()
包括自己 - 但没有进一步的解释。我认为必须有一些原因;为什么它必须彼此不同?
text/template.New()
和html/template.New()
返回的模板都是不具有“正文”的不完整模板,它们还不能用于生成任何输出。如果您尝试执行它们,可以验证这一点:
t := ttemplate.New("t")
h := htemplate.New("h")
fmt.Println(t.Execute(os.Stdout, nil))
fmt.Println(h.Execute(os.Stdout, nil))
输出(在Go Playground上试试):
template: t: "t" is an incomplete or empty template
template: "h" is an incomplete or empty template
返回关联模板中不完整的模板没有意义,是一个实现细节。一个包选择包含它,另一个选择不包括它。
请注意,如果您通过实际解析任何内容来“完成”模板定义,则两者都将包含并返回关联模板中的自我模板,它们之间没有区别:
t := ttemplate.Must(ttemplate.New("t").Parse("t"))
h := htemplate.Must(htemplate.New("h").Parse("h"))
fmt.Println(len(t.Templates()), len(h.Templates()))
fmt.Println(t.Execute(os.Stdout, nil))
fmt.Println(h.Execute(os.Stdout, nil))
这将输出(在Go Playground上尝试):
1 1
t<nil>
h<nil>