1
0
mirror of https://github.com/golang/go synced 2024-11-05 16:16:11 -07:00

text/template: detect unmatched else at parsing time

An unmatched {{else}} should trigger a parsing error.

The top level parser is able to issue an error in case
of unmatched {{end}}. It does it a posteriori (i.e. after having
parsed the action).

Extend this behavior to also check for unmatched {{else}}

Fixes #10611

Change-Id: I1d4f433cc64e11bea5f4d61419ccc707ac01bb1d
Reviewed-on: https://go-review.googlesource.com/9620
Reviewed-by: Rob Pike <r@golang.org>
This commit is contained in:
Didier Spezia 2015-05-01 18:20:31 +00:00 committed by Rob Pike
parent 8a072ada84
commit 80cedf3e8f
2 changed files with 7 additions and 3 deletions

View File

@ -288,11 +288,12 @@ func (t *Tree) parse(treeSet map[string]*Tree) (next Node) {
} }
t.backup2(delim) t.backup2(delim)
} }
n := t.textOrAction() switch n := t.textOrAction(); n.Type() {
if n.Type() == nodeEnd { case nodeEnd, nodeElse:
t.errorf("unexpected %s", n) t.errorf("unexpected %s", n)
default:
t.Root.append(n)
} }
t.Root.append(n)
} }
return nil return nil
} }

View File

@ -230,6 +230,9 @@ var parseTests = []parseTest{
// Errors. // Errors.
{"unclosed action", "hello{{range", hasError, ""}, {"unclosed action", "hello{{range", hasError, ""},
{"unmatched end", "{{end}}", hasError, ""}, {"unmatched end", "{{end}}", hasError, ""},
{"unmatched else", "{{else}}", hasError, ""},
{"unmatched else after if", "{{if .X}}hello{{end}}{{else}}", hasError, ""},
{"multiple else", "{{if .X}}1{{else}}2{{else}}3{{end}}", hasError, ""},
{"missing end", "hello{{range .x}}", hasError, ""}, {"missing end", "hello{{range .x}}", hasError, ""},
{"missing end after else", "hello{{range .x}}{{else}}", hasError, ""}, {"missing end after else", "hello{{range .x}}{{else}}", hasError, ""},
{"undefined function", "hello{{undefined}}", hasError, ""}, {"undefined function", "hello{{undefined}}", hasError, ""},