重新定义 Go 模板:有时有效,有时失败

redefining Go templates: sometimes works, sometimes fails

以下 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 package, which should be "identical" to text/template. It is most of the time, but text/template.Parse() is different, and leaves out this important detail, but they work the same way. This is a documentation inconsistency, filed an issue which can be tracked here: issue #17360 的文档。