go - 重新定义 Go 模板 : sometimes works, 有时会失败

标签 go go-templates

以下 Go 模板处理没有错误:

{{block "A" "hello"}}{{end}}
{{define "A"}}{{.}}{{end}}

输出是“hello”,正如我阅读文档所期望的那样。相反,以下模板不会解析:

{{block "A" "hello"}}A{{end}}
{{define "A"}}{{.}}{{end}}

这里我收到错误消息

template: multiple definition of template "A"

为什么第二个模板会出错,而第一个模板不会出错?这种差异是故意的吗?

完整代码在这里:https://play.golang.org/p/CNAqllVLjB

最佳答案

答案就在 html/template.Parse() 的文档中:

[...] It is an error if a resulting template is non-empty (contains content other than template definitions) and would replace a non-empty template with the same name. (In multiple calls to Parse with the same receiver template, only one call can contain text other than space, comments, and template definitions.)

您的第一个模板之所以有效,是因为 {{block "A"}} 定义了一个空模板,因此允许重新定义它。

您的第二个模板失败,因为 {{block "A"}} 定义了一个非空模板,但您尝试使用非空模板重新定义它。

这里需要注意一件事:我引用了 html/template 中的文档。包,应该与 text/template “相同” 。大多数时候都是这样,但是text/template.Parse()是不同的,并且省略了这个重要的细节,但它们的工作方式是相同的。这是文档不一致,已提交问题,可以在此处跟踪:issue #17360 .

关于go - 重新定义 Go 模板 : sometimes works, 有时会失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39900463/

相关文章:

arrays - 获取嵌套数组中具有特定ObjectId的数组对象

go - 如何为自定义包设置别名?

go - 错误类型 go lang

go - 即时在普罗米修斯中添加指标标签

go - 在 golang 中处理模板错误的惯用方法

go - 如何从多个表中删除记录

go - 简单如果不工作 go 模板

kubernetes - 如何在 Helm 子图中设置与环境相关的 values.yaml?

Golang 函数 'can' t 评估字符串类型的字段'

json - 使用 GO 从文件中解码 JSON 内容并使用 GO 模板包生成 .go 文件