Reputation: 3920
The following Go template processes without error:
{{block "A" "hello"}}{{end}}
{{define "A"}}{{.}}{{end}}
The output is "hello", as I would expect from reading the documentation. In contrast, the following template does not parse:
{{block "A" "hello"}}A{{end}}
{{define "A"}}{{.}}{{end}}
Here I get the error message
template: multiple definition of template "A"
Why does the second template give an error while the first does not? Is this difference intended?
Complete code is here: https://play.golang.org/p/CNAqllVLjB
Upvotes: 2
Views: 580
Reputation: 417402
The answer lies in the doc of 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.)
Your first template works because {{block "A"}}
defines an empty template, and so it is allowed to be re-defined.
Your second template fails because {{block "A"}}
defines a non-empty template and yet you try to re-define it with a non-empty template.
One thing to note here: I quoted the doc from the 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.
Upvotes: 2