以下 Go 模板处理没有错误:
{{block "A" "hello"}}{{end}}
{{define "A"}}{{.}}{{end}}
输出是“hello”,正如我阅读文档所期望的那样。相反,以下模板不会解析:
{{block "A" "hello"}}A{{end}}
{{define "A"}}{{.}}{{end}}
这里我收到错误消息
template: multiple definition of template "A"
为什么第二个模板会出错,而第一个模板不会出错?这种差异是故意的吗?
最佳答案
答案就在 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/