Skip to content

Commit 4869996

Browse files
committed
template: better error message for empty templates
New("x").ParseFiles("y") can result in an empty "x" template. Make the message clearer that this is the problem. The error returns from both template packages in this case were confusing. I considered making the method use "x" instead of "y" in this case, but that just made other situations confusing and harder to explain. Fixes #2594. R=golang-dev, rsc, r CC=golang-dev https://golang.org/cl/5498048
1 parent bbdd207 commit 4869996

File tree

3 files changed

+11
-3
lines changed

3 files changed

+11
-3
lines changed

src/pkg/html/template/escape.go

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -486,9 +486,17 @@ func (e *escaper) escapeTree(c context, name string, line int) (context, string)
486486
}
487487
t := e.template(name)
488488
if t == nil {
489+
// Two cases: The template exists but is empty, or has never been mentioned at
490+
// all. Distinguish the cases in the error messages.
491+
if e.tmpl.set[name] != nil {
492+
return context{
493+
state: stateError,
494+
err: errorf(ErrNoSuchTemplate, line, "%q is an incomplete or empty template", name),
495+
}, dname
496+
}
489497
return context{
490498
state: stateError,
491-
err: errorf(ErrNoSuchTemplate, line, "no such template %s", name),
499+
err: errorf(ErrNoSuchTemplate, line, "no such template %q", name),
492500
}, dname
493501
}
494502
if dname != name {

src/pkg/html/template/escape_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -928,7 +928,7 @@ func TestErrors(t *testing.T) {
928928
},
929929
{
930930
`{{template "foo"}}`,
931-
"z:1: no such template foo",
931+
"z:1: no such template \"foo\"",
932932
},
933933
{
934934
`<div{{template "y"}}>` +

src/pkg/text/template/exec.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,7 @@ func (t *Template) Execute(wr io.Writer, data interface{}) (err error) {
107107
vars: []variable{{"$", value}},
108108
}
109109
if t.Tree == nil || t.Root == nil {
110-
state.errorf("must be parsed before execution")
110+
state.errorf("%q is an incomplete or empty template", t.name)
111111
}
112112
state.walk(value, t.Root)
113113
return

0 commit comments

Comments
 (0)