From 5f6027e9ad9a6f115399a93c5d330cbf2d66e85f Mon Sep 17 00:00:00 2001 From: Rob Pike Date: Mon, 28 Nov 2011 10:42:57 -0800 Subject: [PATCH] text/template: address a couple of issues for html/template - allow Lookup to work on uninitialized templates - fix bug in add: can't error after parser is stopped - add Add method for html/template R=adg, rogpeppe, r, rsc CC=golang-dev https://golang.org/cl/5436080 --- src/pkg/text/template/parse/parse.go | 2 +- src/pkg/text/template/template.go | 20 ++++++++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/src/pkg/text/template/parse/parse.go b/src/pkg/text/template/parse/parse.go index 36c54032ac6..346f613b048 100644 --- a/src/pkg/text/template/parse/parse.go +++ b/src/pkg/text/template/parse/parse.go @@ -170,8 +170,8 @@ func (t *Tree) Parse(s, leftDelim, rightDelim string, treeSet map[string]*Tree, defer t.recover(&err) t.startParse(funcs, lex(t.Name, s, leftDelim, rightDelim)) t.parse(treeSet) - t.stopParse() t.add(treeSet) + t.stopParse() return t, nil } diff --git a/src/pkg/text/template/template.go b/src/pkg/text/template/template.go index aa559fa8afc..c1d0c1c3491 100644 --- a/src/pkg/text/template/template.go +++ b/src/pkg/text/template/template.go @@ -103,6 +103,23 @@ func (t *Template) copy(c *common) *Template { return nt } +// Add associates the argument template, arg, with t, and vice versa, +// so they may invoke each other. To do this, it also removes any +// prior associations arg may have. Except for losing the link to +// arg, templates associated with arg are otherwise unaffected. It +// is an error if the argument template's name is already associated +// with t. Add is here to support html/template and is not intended +// for other uses. +// TODO: make this take a parse.Tree argument instead of a template. +func (t *Template) Add(arg *Template) error { + if t.tmpl[arg.name] != nil { + return fmt.Errorf("template: redefinition of template %q", arg.name) + } + arg.common = t.common + t.tmpl[arg.name] = arg + return nil +} + // Templates returns a slice of the templates associated with t, including t // itself. func (t *Template) Templates() []*Template { @@ -139,6 +156,9 @@ func (t *Template) Funcs(funcMap FuncMap) *Template { // Lookup returns the template with the given name that is associated with t, // or nil if there is no such template. func (t *Template) Lookup(name string) *Template { + if t.common == nil { + return nil + } return t.tmpl[name] }