File: template.go

package info (click to toggle)
golang-github-nicksnyder-go-i18n.v2 2.1.2-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 464 kB
  • sloc: xml: 198; sh: 5; makefile: 3
file content (51 lines) | stat: -rw-r--r-- 1,159 bytes parent folder | download | duplicates (5)
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
package internal

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

// Template stores the template for a string.
type Template struct {
	Src        string
	LeftDelim  string
	RightDelim string

	parseOnce      sync.Once
	parsedTemplate *gotemplate.Template
	parseError     error
}

func (t *Template) Execute(funcs gotemplate.FuncMap, data interface{}) (string, error) {
	leftDelim := t.LeftDelim
	if leftDelim == "" {
		leftDelim = "{{"
	}
	if !strings.Contains(t.Src, leftDelim) {
		// Fast path to avoid parsing a template that has no actions.
		return t.Src, nil
	}

	var gt *gotemplate.Template
	var err error
	if funcs == nil {
		t.parseOnce.Do(func() {
			// If funcs is nil, then we only need to parse this template once.
			t.parsedTemplate, t.parseError = gotemplate.New("").Delims(t.LeftDelim, t.RightDelim).Parse(t.Src)
		})
		gt, err = t.parsedTemplate, t.parseError
	} else {
		gt, err = gotemplate.New("").Delims(t.LeftDelim, t.RightDelim).Funcs(funcs).Parse(t.Src)
	}

	if err != nil {
		return "", err
	}
	var buf bytes.Buffer
	if err := gt.Execute(&buf, data); err != nil {
		return "", err
	}
	return buf.String(), nil
}