This repository has been archived by the owner on Feb 13, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
renderer.go
174 lines (161 loc) · 4.67 KB
/
renderer.go
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
package template
import (
"errors"
"fmt"
htmlplate "html/template"
"io"
"io/ioutil"
"mime"
"os"
"path/filepath"
"regexp"
"github.com/tdewolff/minify"
"github.com/tdewolff/minify/css"
"github.com/tdewolff/minify/html"
"github.com/tdewolff/minify/js"
"github.com/tdewolff/minify/json"
"github.com/tdewolff/minify/xml"
)
// TemplateSet represents a set of 1 or more Go templates.
type TemplateSet struct {
name string
globs []string
renderer *Renderer
templates *htmlplate.Template
}
// Renderer is an object for loading, parsing, minifying and rendering HTML templates.
type Renderer struct {
basePath string
templateSets map[string]*TemplateSet
// Minify is true if the template content should be minified. It's possible that the minification code could have
// problems with complex Go templates, but I've not encountered any problems of that nature so far.
Minify bool
// Live is true if the template sets should be reloaded whenever Execute is used.
// This is obviously a very bad idea in production and should only be used for development.
Live bool
minifier *minify.M
funcmap htmlplate.FuncMap
}
// NewRenderer returns an initialized Renderer. The basepath is used to locate all files subsequently added via Load().
func NewRenderer(basepath string) Renderer {
ren := Renderer{basePath: basepath, templateSets: make(map[string]*TemplateSet)}
min := minify.New()
min.AddFunc("text/html", html.Minify)
min.AddFunc("text/css", css.Minify)
min.AddFuncRegexp(regexp.MustCompile("^(application|text)/(x-)?(java|ecma)script$"), js.Minify)
min.AddFuncRegexp(regexp.MustCompile("[/+]json$"), json.Minify)
min.AddFuncRegexp(regexp.MustCompile("[/+]xml$"), xml.Minify)
ren.minifier = min
return ren
}
// Funcs sets the function map to be used for all subsequent template load operations.
func (tm *Renderer) Funcs(fm htmlplate.FuncMap) {
tm.funcmap = fm
}
// Load loads one or more template files into the specified template set.
func (tm *Renderer) Load(templateSet string, fileglobs ... string) error {
thing := &TemplateSet{
name: templateSet,
globs: fileglobs,
renderer: tm,
}
tm.templateSets[templateSet] = thing
return thing.Load()
}
// Execute executes the named template from the named template set.
func (tm Renderer) Execute(templateSet string, wr io.Writer, tmplname string, data interface{}) error {
var err error
tmpl, ok := tm.templateSets[templateSet]
if ok {
if tm.Live {
err = tmpl.Load()
if err != nil {
return err
}
}
err = tmpl.execute(wr, tmplname, data)
} else {
err = fmt.Errorf("no such template file set %s", templateSet)
}
return err
}
// Reload reloads the named template set.
func (tm Renderer) Reload(templateSet string) error {
var err error
thing, ok := tm.templateSets[templateSet]
if ok {
err = thing.Load()
} else {
err = fmt.Errorf("reload failed, file set %s unknown", templateSet)
}
return err
}
// minify handles minification of loaded file data
func (tm Renderer) minify(filename string, dat []byte) (string, error) {
if !tm.Minify {
return string(dat), nil
}
var err error
ext := filepath.Ext(filename)
mtype := mime.TypeByExtension(ext)
_, _, mfn := tm.minifier.Match(mtype)
if mfn != nil {
dat, err = tm.minifier.Bytes(mtype, dat)
}
return string(dat), err
}
// Load causes a template set to be loaded from the files in the filesystem.
// Minification is performed if configured, and the template files are compiled.
func (th *TemplateSet) Load() error {
var tmpl *htmlplate.Template
for _, glob := range th.globs {
globpath := filepath.Join(th.renderer.basePath, glob)
matches, err := filepath.Glob(globpath)
if err != nil {
return err
}
for _, filename := range matches {
fi, err := os.Stat(filename)
if err != nil {
return err
}
if fi.IsDir() {
continue
}
name, err := filepath.Rel(th.renderer.basePath, filename)
if err != nil {
return err
}
data, err := ioutil.ReadFile(filename)
if err != nil {
return err
}
dat, err := th.renderer.minify(filename, data)
if err != nil {
return err
}
if tmpl == nil {
fmap := th.renderer.funcmap
if fmap != nil {
tmpl, err = htmlplate.New(name).Funcs(th.renderer.funcmap).Parse(dat)
} else {
tmpl, err = htmlplate.New(name).Parse(dat)
}
} else {
tmpl, err = tmpl.New(name).Parse(dat)
}
if err != nil {
return err
}
}
}
th.templates = tmpl
return nil
}
// execute executes an individual template set.
func (th TemplateSet) execute(wr io.Writer, tmplname string, data interface{}) error {
if th.templates == nil {
return errors.New("no templates in template set")
}
return th.templates.ExecuteTemplate(wr, tmplname, data)
}