bou.ke/statictemplate@v0.0.0-20180821122055-510411a5e7dd/statictemplate/wrapper.go (about) 1 package statictemplate 2 3 import ( 4 htmlTemplate "html/template" 5 textTemplate "text/template" 6 "text/template/parse" 7 _ "unsafe" 8 ) 9 10 type wrappedTemplate interface { 11 Tree() *parse.Tree 12 Lookup(name string) (wrappedTemplate, error) 13 Name() string 14 } 15 16 type textTemplateWrapper struct { 17 *textTemplate.Template 18 } 19 20 var _ wrappedTemplate = textTemplateWrapper{} 21 22 func (t textTemplateWrapper) Tree() *parse.Tree { 23 return t.Template.Tree 24 } 25 26 func (t textTemplateWrapper) Lookup(name string) (wrappedTemplate, error) { 27 return textTemplateWrapper{t.Template.Lookup(name)}, nil 28 } 29 30 type htmlTemplateWrapper struct { 31 *htmlTemplate.Template 32 } 33 34 var _ wrappedTemplate = htmlTemplateWrapper{} 35 36 func (t htmlTemplateWrapper) Tree() *parse.Tree { 37 return t.Template.Tree 38 } 39 40 func (t htmlTemplateWrapper) Lookup(name string) (wrappedTemplate, error) { 41 temp, err := lookupAndEscapeTemplate(t.Template, name) 42 return htmlTemplateWrapper{temp}, err 43 } 44 45 func wrap(template interface{}) wrappedTemplate { 46 switch template := template.(type) { 47 case *htmlTemplate.Template: 48 return htmlTemplateWrapper{template} 49 case *textTemplate.Template: 50 return textTemplateWrapper{template} 51 default: 52 panic("invalid template passed in") 53 } 54 } 55 56 //go:linkname lookupAndEscapeTemplate html/template.(*Template).lookupAndEscapeTemplate 57 func lookupAndEscapeTemplate(t *htmlTemplate.Template, name string) (*htmlTemplate.Template, error)