1
2
3
4
5
6
7 package lazytemplate
8
9 import (
10 "io"
11 "os"
12 "strings"
13 "sync"
14 "text/template"
15 )
16
17
18
19 type Template struct {
20 name, text string
21
22 once sync.Once
23 tmpl *template.Template
24 }
25
26 func (r *Template) tp() *template.Template {
27 r.once.Do(r.build)
28 return r.tmpl
29 }
30
31 func (r *Template) build() {
32 r.tmpl = template.Must(template.New(r.name).Parse(r.text))
33 r.name, r.text = "", ""
34 }
35
36 func (r *Template) Execute(w io.Writer, data any) error {
37 return r.tp().Execute(w, data)
38 }
39
40 var inTest = len(os.Args) > 0 && strings.HasSuffix(strings.TrimSuffix(os.Args[0], ".exe"), ".test")
41
42
43
44
45 func New(name, text string) *Template {
46 lt := &Template{name: name, text: text}
47 if inTest {
48
49 lt.tp()
50 }
51 return lt
52 }
53
View as plain text