From 2b583a190eb14c69bffe5d488d2d6d3862fe76ea Mon Sep 17 00:00:00 2001 From: Jess Frazelle Date: Wed, 22 Jun 2016 21:57:52 -0700 Subject: [PATCH] text/template: fix Parse when called twice with empty text Fixes #16156 Change-Id: I6989db4fd392583a2d490339cefc525b07c11b90 Reviewed-on: https://go-review.googlesource.com/24380 Reviewed-by: Andrew Gerrand Run-TryBot: Andrew Gerrand --- src/text/template/multi_test.go | 36 +++++++++++++++++++++++++++++++++ src/text/template/template.go | 2 +- 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/src/text/template/multi_test.go b/src/text/template/multi_test.go index c8723cb7a8b..8142f008fdf 100644 --- a/src/text/template/multi_test.go +++ b/src/text/template/multi_test.go @@ -349,3 +349,39 @@ func TestParse(t *testing.T) { t.Fatalf("parsing test: %s", err) } } + +func TestEmptyTemplate(t *testing.T) { + cases := []struct { + defn []string + in string + want string + }{ + {[]string{""}, "once", ""}, + {[]string{"", ""}, "twice", ""}, + {[]string{"{{.}}", "{{.}}"}, "twice", "twice"}, + {[]string{"{{/* a comment */}}", "{{/* a comment */}}"}, "comment", ""}, + {[]string{"{{.}}", ""}, "twice", ""}, + } + + for _, c := range cases { + root := New("root") + + var ( + m *Template + err error + ) + for _, d := range c.defn { + m, err = root.New(c.in).Parse(d) + if err != nil { + t.Fatal(err) + } + } + buf := &bytes.Buffer{} + if err := m.Execute(buf, c.in); err != nil { + t.Fatal(err) + } + if buf.String() != c.want { + t.Errorf("expected string %q: got %q", c.want, buf.String()) + } + } +} diff --git a/src/text/template/template.go b/src/text/template/template.go index 7a7f42a7153..a8ad6279e30 100644 --- a/src/text/template/template.go +++ b/src/text/template/template.go @@ -208,7 +208,7 @@ func (t *Template) associate(new *Template, tree *parse.Tree) (bool, error) { if new.common != t.common { panic("internal error: associate not common") } - if t.tmpl[new.name] != nil && parse.IsEmptyTree(tree.Root) { + if t.tmpl[new.name] != nil && parse.IsEmptyTree(tree.Root) && t.Tree != nil { // If a template by that name exists, // don't replace it with an empty template. return false, nil