gpt4 book ai didi

go - text/template.Templates 和 html/template.Templates 之间的区别

转载 作者:IT王子 更新时间:2023-10-29 01:43:48 31 4
gpt4 key购买 nike

最近,我注意到 html/template.TemplateTemplates()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>

关于go - text/template.Templates 和 html/template.Templates 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55265456/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com