text/template.Templates 和 html/template.Templates 之间的区别
Difference between text/template.Templates and html/template.Templates
最近,我注意到 html/template.Template
的 Templates()
与 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()
and html/template.New()
编辑的 return 模板都是 不完整的模板 ,没有 "body",它们还不能用于生成任何输出。如果您尝试执行它们,您可以验证这一点:
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
在关联模板中返回不完整的模板没有意义,是一个实现细节。一个包选择包含它,另一个选择不包含。
请注意,如果您 "complete" 通过实际解析任何内容来定义模板,两者都将包括 return 关联模板中的自身模板,它们之间没有区别:
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>
最近,我注意到 html/template.Template
的 Templates()
与 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()
and html/template.New()
编辑的 return 模板都是 不完整的模板 ,没有 "body",它们还不能用于生成任何输出。如果您尝试执行它们,您可以验证这一点:
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
在关联模板中返回不完整的模板没有意义,是一个实现细节。一个包选择包含它,另一个选择不包含。
请注意,如果您 "complete" 通过实际解析任何内容来定义模板,两者都将包括 return 关联模板中的自身模板,它们之间没有区别:
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>