登录
首页 >  Golang >  Go问答

区分text/template.Templates 和 html/template.Templates

来源:stackoverflow

时间:2024-03-20 08:45:31 203浏览 收藏

文本模板(text/template)和 HTML 模板(html/template)在 Go 语言中用于生成动态文本。它们创建的模板不完整,需要进一步解析才能生成输出。text/template 在关联模板中不包含自身模板,而 html/template 则包含。这只是一个实现细节,不影响模板的功能。当模板被解析后,两个模板库都会在关联模板中包含自身模板,并且可以正常使用。

问题内容

最近,我注意到 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
h

本篇关于《区分text/template.Templates 和 html/template.Templates》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>