From 12dfc3bee482f16263ce4673a0cce399127e2a0d Mon Sep 17 00:00:00 2001 From: Andrew Gerrand Date: Fri, 28 Aug 2015 15:31:51 +1000 Subject: text/template, html/template: add block keyword and permit template redefinition This change adds a new "block" keyword that permits the definition of templates inline inside existing templates, and loosens the restriction on template redefinition. Templates may now be redefined, but in the html/template package they may only be redefined before the template is executed (and therefore escaped). The intention is that such inline templates can be redefined by subsequent template definitions, permitting a kind of template "inheritance" or "overlay". (See the example for details.) Fixes #3812 Change-Id: I733cb5332c1c201c235f759cc64333462e70dc27 Reviewed-on: https://go-review.googlesource.com/14005 Reviewed-by: Rob Pike --- src/text/template/exec_test.go | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) (limited to 'src/text/template/exec_test.go') diff --git a/src/text/template/exec_test.go b/src/text/template/exec_test.go index 139fc5320d..f9cb03eead 100644 --- a/src/text/template/exec_test.go +++ b/src/text/template/exec_test.go @@ -1232,3 +1232,36 @@ func testBadFuncName(name string, t *testing.T) { // reports an error. t.Errorf("%q succeeded incorrectly as function name", name) } + +func TestBlock(t *testing.T) { + const ( + input = `a({{block "inner" .}}bar({{.}})baz{{end}})b` + want = `a(bar(hello)baz)b` + overlay = `{{define "inner"}}foo({{.}})bar{{end}}` + want2 = `a(foo(goodbye)bar)b` + ) + tmpl, err := New("outer").Parse(input) + if err != nil { + t.Fatal(err) + } + tmpl2, err := Must(tmpl.Clone()).Parse(overlay) + if err != nil { + t.Fatal(err) + } + + var buf bytes.Buffer + if err := tmpl.Execute(&buf, "hello"); err != nil { + t.Fatal(err) + } + if got := buf.String(); got != want { + t.Errorf("got %q, want %q", got, want) + } + + buf.Reset() + if err := tmpl2.Execute(&buf, "goodbye"); err != nil { + t.Fatal(err) + } + if got := buf.String(); got != want2 { + t.Errorf("got %q, want %q", got, want2) + } +} -- cgit v1.3-5-g9baa