summaryrefslogtreecommitdiffstats
path: root/vendor/github.com/nicksnyder/go-i18n/i18n/translation/template.go
blob: c8756fa4e0573f9977c980ff72fb200971d64c25 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package translation

import (
	"bytes"
	"encoding"
	"strings"
	gotemplate "text/template"
)

type template struct {
	tmpl *gotemplate.Template
	src  string
}

func newTemplate(src string) (*template, error) {
	var tmpl template
	err := tmpl.parseTemplate(src)
	return &tmpl, err
}

func mustNewTemplate(src string) *template {
	t, err := newTemplate(src)
	if err != nil {
		panic(err)
	}
	return t
}

func (t *template) String() string {
	return t.src
}

func (t *template) Execute(args interface{}) string {
	if t.tmpl == nil {
		return t.src
	}
	var buf bytes.Buffer
	if err := t.tmpl.Execute(&buf, args); err != nil {
		return err.Error()
	}
	return buf.String()
}

func (t *template) MarshalText() ([]byte, error) {
	return []byte(t.src), nil
}

func (t *template) UnmarshalText(src []byte) error {
	return t.parseTemplate(string(src))
}

func (t *template) parseTemplate(src string) (err error) {
	t.src = src
	if strings.Contains(src, "{{") {
		t.tmpl, err = gotemplate.New(src).Parse(src)
	}
	return
}

var _ = encoding.TextMarshaler(&template{})
var _ = encoding.TextUnmarshaler(&template{})