/
engine.go
272 lines (233 loc) · 6.41 KB
/
engine.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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
package gotemplate
import (
"bytes"
"context"
"fmt"
"html/template"
"io"
"io/ioutil"
"os"
"path/filepath"
"strings"
"sync"
"time"
"flamingo.me/flamingo/framework/flamingo"
"flamingo.me/flamingo/framework/router"
flamingotemplate "flamingo.me/flamingo/framework/template"
"github.com/pkg/errors"
"go.opencensus.io/trace"
)
const pathSeparatorString = string(os.PathSeparator)
type (
engine struct {
templatesBasePath string
layoutTemplatesDir string
debug bool
tplFuncs flamingotemplate.FuncProvider
tplCtxFuncs flamingotemplate.CtxFuncProvider
templates map[string]*template.Template
logger flamingo.Logger
}
// urlFunc allows templates to access the routers `URL` helper method
urlFunc struct {
Router *router.Router `inject:""`
}
// getFunc allows templates to access the router's `get` method
dataFunc struct {
Router *router.Router `inject:""`
}
getFunc struct {
Router *router.Router `inject:""`
}
)
var (
_ flamingotemplate.Func = new(urlFunc)
_ flamingotemplate.CtxFunc = new(getFunc)
_ flamingotemplate.CtxFunc = new(dataFunc)
lock = &sync.Mutex{}
)
// Inject engine dependencies
func (e *engine) Inject(
tplFuncs flamingotemplate.FuncProvider,
tplCtxFuncs flamingotemplate.CtxFuncProvider,
logger flamingo.Logger,
config *struct {
TemplatesBasePath string `inject:"config:gotemplates.engine.templates.basepath"`
LayoutTemplatesDir string `inject:"config:gotemplates.engine.layout.dir"`
Debug bool `inject:"config:debug.mode"`
},
) {
e.tplFuncs = tplFuncs
e.tplCtxFuncs = tplCtxFuncs
e.templatesBasePath = config.TemplatesBasePath
e.layoutTemplatesDir = config.LayoutTemplatesDir
e.debug = config.Debug
e.logger = logger
}
func (e *engine) Render(ctx context.Context, name string, data interface{}) (io.Reader, error) {
ctx, span := trace.StartSpan(ctx, "gotemplate/Render")
defer span.End()
lock.Lock()
if e.debug || e.templates == nil {
err := e.loadTemplates(ctx)
if err != nil {
return nil, err
}
}
lock.Unlock()
_, span = trace.StartSpan(ctx, "gotemplate/Execute")
buf := &bytes.Buffer{}
if _, ok := e.templates[name+".html"]; !ok {
return nil, errors.New("Could not find the template " + name + ".html")
}
tpl, err := e.templates[name+".html"].Clone()
if err != nil {
return nil, err
}
tplFuncs := template.FuncMap{}
for k, f := range e.tplCtxFuncs() {
tplFuncs[k] = f.Func(ctx)
}
tpl.Funcs(tplFuncs)
err = tpl.Execute(buf, data)
defer span.End()
return buf, err
}
func (e *engine) loadTemplates(ctx context.Context) error {
ctx, span := trace.StartSpan(ctx, "gotemplate/loadTemplates")
defer span.End()
e.templates = make(map[string]*template.Template, 0)
functionsMap := template.FuncMap{
"Upper": strings.ToUpper,
"formatDate": func(t time.Time) string {
return t.Format("2006-01-02")
},
"map": func(p ...interface{}) map[string]interface{} {
res := make(map[string]interface{})
for i := 0; i < len(p); i += 2 {
res[fmt.Sprint(p[i])] = p[i+1]
}
return res
},
}
tplFuncs := template.FuncMap{}
for k, f := range e.tplFuncs() {
tplFuncs[k] = f.Func()
}
for k, f := range e.tplCtxFuncs() {
tplFuncs[k] = f.Func(ctx)
}
layoutTemplate, err := e.parseLayoutTemplates(functionsMap, tplFuncs)
if err != nil {
return err
}
err = e.parseSiteTemplateDirectory(layoutTemplate, e.templatesBasePath)
if err != nil {
return err
}
return nil
}
// parses all layout templates in a template instance which is the base instance for all other templates
func (e *engine) parseLayoutTemplates(functionsMap template.FuncMap, funcs template.FuncMap) (*template.Template, error) {
tpl := template.New("").Funcs(functionsMap).Funcs(funcs)
if e.layoutTemplatesDir == "" {
return tpl, nil
}
dir := e.templatesBasePath + pathSeparatorString + e.layoutTemplatesDir
layoutFilesNames := make([]string, 0)
err := filepath.Walk(
dir,
func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() {
return nil
}
layoutFilesNames = append(layoutFilesNames, path)
return nil
},
)
if err != nil {
return nil, err
}
for _, file := range layoutFilesNames {
tContent, err := ioutil.ReadFile(file)
if err != nil {
return nil, err
}
templateName, err := filepath.Rel(dir, file)
t := tpl.New(templateName)
_, err = t.Parse(string(tContent))
if err != nil {
return nil, err
}
}
return tpl, nil
}
// parses all templates from a given directory into a clone of the given layout template, so that all layouts are available
func (e *engine) parseSiteTemplateDirectory(layoutTemplate *template.Template, dir string) error {
files, err := ioutil.ReadDir(dir)
if err != nil {
return err
}
for _, f := range files {
t := template.Must(layoutTemplate.Clone())
fullName := dir + pathSeparatorString + f.Name()
if f.IsDir() {
err = e.parseSiteTemplateDirectory(layoutTemplate, fullName)
if err != nil {
return err
}
continue
}
tContent, err := ioutil.ReadFile(fullName)
if err != nil {
return err
}
templateName := strings.TrimPrefix(fullName, e.templatesBasePath+pathSeparatorString)
parsedTemplate, err := t.Parse(string(tContent))
if err != nil {
e.logger.WithField("category", "gotemplate").Error(err)
continue
}
e.templates[templateName] = template.Must(parsedTemplate, err)
}
return nil
}
// Func as implementation of get method
func (g *getFunc) Func(ctx context.Context) interface{} {
return func(what string, params ...map[string]interface{}) interface{} {
var p = make(map[interface{}]interface{})
if len(params) == 1 {
for k, v := range params[0] {
p[k] = fmt.Sprint(v)
}
}
return g.Router.Data(ctx, what, p)
}
}
// Func as implementation of get method
func (d *dataFunc) Func(ctx context.Context) interface{} {
return func(what string, params ...map[string]interface{}) interface{} {
var p = make(map[interface{}]interface{})
if len(params) == 1 {
for k, v := range params[0] {
p[k] = fmt.Sprint(v)
}
}
return d.Router.Data(ctx, what, p)
}
}
// Func as implementation of url method
func (u *urlFunc) Func() interface{} {
return func(where string, params ...map[string]interface{}) template.URL {
var p = make(map[string]string)
if len(params) == 1 {
for k, v := range params[0] {
p[k] = fmt.Sprint(v)
}
}
return template.URL(u.Router.URL(where, p).String())
}
}