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