1package translation 2 3import ( 4 "bytes" 5 "encoding" 6 "strings" 7 gotemplate "text/template" 8) 9 10type template struct { 11 tmpl *gotemplate.Template 12 src string 13} 14 15func newTemplate(src string) (*template, error) { 16 if src == "" { 17 return new(template), nil 18 } 19 20 var tmpl template 21 err := tmpl.parseTemplate(src) 22 return &tmpl, err 23} 24 25func mustNewTemplate(src string) *template { 26 t, err := newTemplate(src) 27 if err != nil { 28 panic(err) 29 } 30 return t 31} 32 33func (t *template) String() string { 34 return t.src 35} 36 37func (t *template) Execute(args interface{}) string { 38 if t.tmpl == nil { 39 return t.src 40 } 41 var buf bytes.Buffer 42 if err := t.tmpl.Execute(&buf, args); err != nil { 43 return err.Error() 44 } 45 return buf.String() 46} 47 48func (t *template) MarshalText() ([]byte, error) { 49 return []byte(t.src), nil 50} 51 52func (t *template) UnmarshalText(src []byte) error { 53 return t.parseTemplate(string(src)) 54} 55 56func (t *template) parseTemplate(src string) (err error) { 57 t.src = src 58 if strings.Contains(src, "{{") { 59 t.tmpl, err = gotemplate.New(src).Parse(src) 60 } 61 return 62} 63 64var _ = encoding.TextMarshaler(&template{}) 65var _ = encoding.TextUnmarshaler(&template{}) 66