Debian Codegraph @

debian/go/src/github.com/gohugoio/go-i18n/v2/i18n/template/text_parser.go

raw
1 package template
2
3 import (
4 "bytes"
5 "strings"
6 "text/template"
7 )
8
9 // TextParser is a Parser that uses text/template.
10 type TextParser struct {
11 LeftDelim string
12 RightDelim string
13 Funcs template.FuncMap
14 Option string
15 }
16
17 func (te *TextParser) Cacheable() bool {
18 return te.Funcs == nil
19 }
20
21 func (te *TextParser) Parse(src, leftDelim, rightDelim string) (ParsedTemplate, error) {
22 if leftDelim == "" {
23 leftDelim = te.LeftDelim
24 }
25 if leftDelim == "" {
26 leftDelim = "{{"
27 }
28 if !strings.Contains(src, leftDelim) {
29 // Fast path to avoid parsing a template that has no actions.
30 return &identityParsedTemplate{src: src}, nil
31 }
32
33 if rightDelim == "" {
34 rightDelim = te.RightDelim
35 }
36 if rightDelim == "" {
37 rightDelim = "}}"
38 }
39
40 option := "missingkey=default"
41 if te.Option != "" {
42 option = te.Option
43 }
44
45 tmpl, err := template.New("").Delims(leftDelim, rightDelim).Option(option).Funcs(te.Funcs).Parse(src)
46 if err != nil {
47 return nil, err
48 }
49 return &parsedTextTemplate{tmpl: tmpl}, nil
50 }
51
52 type parsedTextTemplate struct {
53 tmpl *template.Template
54 }
55
56 func (t *parsedTextTemplate) Execute(data any) (string, error) {
57 var buf bytes.Buffer
58 if err := t.tmpl.Execute(&buf, data); err != nil {
59 return "", err
60 }
61 return buf.String(), nil
62 }