Beispiel #1
0
// Returns a copy of the root template with the supplied template merged in.
func (ts *Templates) mergeTemplate(t *template.Template) (out *template.Template, err error) {
	defer func() {
		if r := recover(); r != nil {
			// Seems to be a bug with cloning empty templates.
			err = fmt.Errorf("Problem cloning template: %v", r)
		}
	}()
	if ts.empty {
		out = template.New("root")
	} else {
		if out, err = ts.root.Clone(); err != nil {
			return
		}
	}
	for _, tmpl := range t.Templates() {
		ptr := out.Lookup(tmpl.Name())
		if ptr == nil {
			out.Parse(fmt.Sprintf(`{{define "%v"}}{{end}}`, tmpl.Name()))
			ptr = out.Lookup(tmpl.Name())
		}
		var clone *template.Template
		if clone, err = tmpl.Clone(); err != nil {
			return
		}
		(*ptr) = *clone
		// Merge existing root templates back into new template.
		for _, out_tmpl := range out.Templates() {
			ptr2 := clone.Lookup(out_tmpl.Name())
			if ptr2 == nil {
				clone.Parse(fmt.Sprintf(`{{define "%v"}}{{end}}`, out_tmpl.Name()))
				ptr2 = clone.Lookup(out_tmpl.Name())
				(*ptr2) = *out_tmpl
			}
		}
	}
	return
}