summaryrefslogtreecommitdiff
path: root/pkg/templates.go
blob: 736bbe0c72ca4b187c7ee1c1f45f0e43649c9caa (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
package gonf

import (
	"bytes"
	"log/slog"
	"strconv"
	"text/template"
)

// ----- Globals ---------------------------------------------------------------
var templates *template.Template

// ----- Init ------------------------------------------------------------------
func init() {
	templates = template.New("")
	templates.Option("missingkey=error")
	templates.Funcs(builtinTemplateFunctions)
}

// ----- Public ----------------------------------------------------------------
type TemplateValue struct {
	contents []byte
	data     string
}

func (t *TemplateValue) Bytes() []byte {
	if t.contents == nil {
		tpl := templates.New("")
		if _, err := tpl.Parse(t.data); err != nil {
			slog.Error("template", "step", "Parse", "data", t.data, "error", err)
			return nil
		}
		var buff bytes.Buffer
		if err := tpl.Execute(&buff, nil /* no data needed */); err != nil {
			slog.Error("template", "step", "Execute", "data", t.data, "error", err)
			return nil
		}
		t.contents = buff.Bytes()
	}
	return t.contents
}
func (t TemplateValue) Int() (int, error) {
	return strconv.Atoi(t.String())
}
func (t TemplateValue) String() string {
	return string(t.Bytes()[:])
}