forked from revel/revel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
template.go
498 lines (438 loc) · 14.7 KB
/
template.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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
package revel
import (
"fmt"
"html"
"html/template"
"io"
"io/ioutil"
"log"
"os"
"path/filepath"
"reflect"
"regexp"
"strconv"
"strings"
"time"
)
var ERROR_CLASS = "hasError"
// This object handles loading and parsing of templates.
// Everything below the application's views directory is treated as a template.
type TemplateLoader struct {
// This is the set of all templates under views
templateSet *template.Template
// If an error was encountered parsing the templates, it is stored here.
compileError *Error
// Paths to search for templates, in priority order.
paths []string
// Map from template name to the path from whence it was loaded.
templatePaths map[string]string
// templateNames is a map from lower case template name to the real template name.
templateNames map[string]string
}
type Template interface {
Name() string
Content() []string
Render(wr io.Writer, arg interface{}) error
}
var invalidSlugPattern = regexp.MustCompile(`[^a-z0-9 _-]`)
var whiteSpacePattern = regexp.MustCompile(`\s+`)
var (
// The functions available for use in the templates.
TemplateFuncs = map[string]interface{}{
"url": ReverseUrl,
"set": func(renderArgs map[string]interface{}, key string, value interface{}) template.JS {
renderArgs[key] = value
return template.JS("")
},
"append": func(renderArgs map[string]interface{}, key string, value interface{}) template.JS {
if renderArgs[key] == nil {
renderArgs[key] = []interface{}{value}
} else {
renderArgs[key] = append(renderArgs[key].([]interface{}), value)
}
return template.JS("")
},
"field": NewField,
"firstof": func(args ...interface{}) interface{} {
for _, val := range args {
switch val.(type) {
case nil:
continue
case string:
if val == "" {
continue
}
return val
default:
return val
}
}
return nil
},
"option": func(f *Field, val interface{}, label string) template.HTML {
selected := ""
if f.Flash() == val || (f.Flash() == "" && f.Value() == val) {
selected = " selected"
}
return template.HTML(fmt.Sprintf(`<option value="%s"%s>%s</option>`,
html.EscapeString(fmt.Sprintf("%v", val)), selected, html.EscapeString(label)))
},
"radio": func(f *Field, val string) template.HTML {
checked := ""
if f.Flash() == val {
checked = " checked"
}
return template.HTML(fmt.Sprintf(`<input type="radio" name="%s" value="%s"%s>`,
html.EscapeString(f.Name), html.EscapeString(val), checked))
},
"checkbox": func(f *Field, val string) template.HTML {
checked := ""
if f.Flash() == val {
checked = " checked"
}
return template.HTML(fmt.Sprintf(`<input type="checkbox" name="%s" value="%s"%s>`,
html.EscapeString(f.Name), html.EscapeString(val), checked))
},
// Pads the given string with 's up to the given width.
"pad": func(str string, width int) template.HTML {
if len(str) >= width {
return template.HTML(html.EscapeString(str))
}
return template.HTML(html.EscapeString(str) + strings.Repeat(" ", width-len(str)))
},
"errorClass": func(name string, renderArgs map[string]interface{}) template.HTML {
errorMap, ok := renderArgs["errors"].(map[string]*ValidationError)
if !ok || errorMap == nil {
WARN.Println("Called 'errorClass' without 'errors' in the render args.")
return template.HTML("")
}
valError, ok := errorMap[name]
if !ok || valError == nil {
return template.HTML("")
}
return template.HTML(ERROR_CLASS)
},
"msg": func(renderArgs map[string]interface{}, message string, args ...interface{}) template.HTML {
str, ok := renderArgs[CurrentLocaleRenderArg].(string)
if !ok {
return ""
}
return template.HTML(Message(str, message, args...))
},
// Replaces newlines with <br>
"nl2br": func(text string) template.HTML {
return template.HTML(strings.Replace(template.HTMLEscapeString(text), "\n", "<br>", -1))
},
// Skips sanitation on the parameter. Do not use with dynamic data.
"raw": func(text string) template.HTML {
return template.HTML(text)
},
// Pluralize, a helper for pluralizing words to correspond to data of dynamic length.
// items - a slice of items, or an integer indicating how many items there are.
// pluralOverrides - optional arguments specifying the output in the
// singular and plural cases. by default "" and "s"
"pluralize": func(items interface{}, pluralOverrides ...string) string {
singular, plural := "", "s"
if len(pluralOverrides) >= 1 {
singular = pluralOverrides[0]
if len(pluralOverrides) == 2 {
plural = pluralOverrides[1]
}
}
switch v := reflect.ValueOf(items); v.Kind() {
case reflect.Int:
if items.(int) != 1 {
return plural
}
case reflect.Slice:
if v.Len() != 1 {
return plural
}
default:
ERROR.Println("pluralize: unexpected type: ", v)
}
return singular
},
// Format a date according to the application's default date(time) format.
"date": func(date time.Time) string {
return date.Format(DateFormat)
},
"datetime": func(date time.Time) string {
return date.Format(DateTimeFormat)
},
"slug": Slug,
"even": func(a int) bool { return (a % 2) == 0 },
}
)
func NewTemplateLoader(paths []string) *TemplateLoader {
loader := &TemplateLoader{
paths: paths,
}
return loader
}
// This scans the views directory and parses all templates as Go Templates.
// If a template fails to parse, the error is set on the loader.
// (It's awkward to refresh a single Go Template)
func (loader *TemplateLoader) Refresh() *Error {
TRACE.Printf("Refreshing templates from %s", loader.paths)
loader.compileError = nil
loader.templatePaths = map[string]string{}
loader.templateNames = map[string]string{}
// Set the template delimiters for the project if present, then split into left
// and right delimiters around a space character
var splitDelims []string
if TemplateDelims != "" {
splitDelims = strings.Split(TemplateDelims, " ")
if len(splitDelims) != 2 {
log.Fatalln("app.conf: Incorrect format for template.delimiters")
}
}
// Walk through the template loader's paths and build up a template set.
var templateSet *template.Template = nil
for _, basePath := range loader.paths {
// Walk only returns an error if the template loader is completely unusable
// (namely, if one of the TemplateFuncs does not have an acceptable signature).
// Handling symlinked directories
var fullSrcDir string
f, err := os.Lstat(basePath)
if err == nil && f.Mode()&os.ModeSymlink == os.ModeSymlink {
fullSrcDir, err = filepath.EvalSymlinks(basePath)
if err != nil {
panic(err)
}
} else {
fullSrcDir = basePath
}
var templateWalker func(path string, info os.FileInfo, err error) error
templateWalker = func(path string, info os.FileInfo, err error) error {
if err != nil {
ERROR.Println("error walking templates:", err)
return nil
}
// is it a symlinked template?
link, err := os.Lstat(path)
if err == nil && link.Mode()&os.ModeSymlink == os.ModeSymlink {
TRACE.Println("symlink template:", path)
// lookup the actual target & check for goodness
targetPath, err := filepath.EvalSymlinks(path)
if err != nil {
ERROR.Println("Failed to read symlink", err)
return err
}
targetInfo, err := os.Stat(targetPath)
if err != nil {
ERROR.Println("Failed to stat symlink target", err)
return err
}
// set the template path to the target of the symlink
path = targetPath
info = targetInfo
// need to save state and restore for recursive call to Walk on symlink
tmp := fullSrcDir
fullSrcDir = filepath.Dir(targetPath)
filepath.Walk(targetPath, templateWalker)
fullSrcDir = tmp
}
// Walk into watchable directories
if info.IsDir() {
if !loader.WatchDir(info) {
return filepath.SkipDir
}
return nil
}
// Only add watchable
if !loader.WatchFile(info.Name()) {
return nil
}
var fileStr string
// addTemplate loads a template file into the Go template loader so it can be rendered later
addTemplate := func(templateName string) (err error) {
TRACE.Println("adding template: ", templateName)
// Convert template names to use forward slashes, even on Windows.
if os.PathSeparator == '\\' {
templateName = strings.Replace(templateName, `\`, `/`, -1) // `
}
// If we already loaded a template of this name, skip it.
lowerTemplateName := strings.ToLower(templateName)
if _, ok := loader.templateNames[lowerTemplateName]; ok {
return nil
}
loader.templatePaths[templateName] = path
loader.templateNames[lowerTemplateName] = templateName
// Load the file if we haven't already
if fileStr == "" {
fileBytes, err := ioutil.ReadFile(path)
if err != nil {
ERROR.Println("Failed reading file:", path)
return nil
}
fileStr = string(fileBytes)
}
if templateSet == nil {
// Create the template set. This panics if any of the funcs do not
// conform to expectations, so we wrap it in a func and handle those
// panics by serving an error page.
var funcError *Error
func() {
defer func() {
if err := recover(); err != nil {
funcError = &Error{
Title: "Panic (Template Loader)",
Description: fmt.Sprintln(err),
}
}
}()
templateSet = template.New(templateName).Funcs(TemplateFuncs)
// If alternate delimiters set for the project, change them for this set
if splitDelims != nil && basePath == ViewsPath {
templateSet.Delims(splitDelims[0], splitDelims[1])
} else {
// Reset to default otherwise
templateSet.Delims("", "")
}
_, err = templateSet.Parse(fileStr)
}()
if funcError != nil {
return funcError
}
} else {
if splitDelims != nil && basePath == ViewsPath {
templateSet.Delims(splitDelims[0], splitDelims[1])
} else {
templateSet.Delims("", "")
}
_, err = templateSet.New(templateName).Parse(fileStr)
}
return err
}
templateName := path[len(fullSrcDir)+1:]
err = addTemplate(templateName)
// Store / report the first error encountered.
if err != nil && loader.compileError == nil {
_, line, description := parseTemplateError(err)
loader.compileError = &Error{
Title: "Template Compilation Error",
Path: templateName,
Description: description,
Line: line,
SourceLines: strings.Split(fileStr, "\n"),
}
ERROR.Printf("Template compilation error (In %s around line %d):\n%s",
templateName, line, description)
}
return nil
}
funcErr := filepath.Walk(fullSrcDir, templateWalker)
// If there was an error with the Funcs, set it and return immediately.
if funcErr != nil {
loader.compileError = funcErr.(*Error)
return loader.compileError
}
}
// Note: compileError may or may not be set.
loader.templateSet = templateSet
return loader.compileError
}
func (loader *TemplateLoader) WatchDir(info os.FileInfo) bool {
// Watch all directories, except the ones starting with a dot.
return !strings.HasPrefix(info.Name(), ".")
}
func (loader *TemplateLoader) WatchFile(basename string) bool {
// Watch all files, except the ones starting with a dot.
return !strings.HasPrefix(basename, ".")
}
// Parse the line, and description from an error message like:
// html/template:Application/Register.html:36: no such template "footer.html"
func parseTemplateError(err error) (templateName string, line int, description string) {
description = err.Error()
i := regexp.MustCompile(`:\d+:`).FindStringIndex(description)
if i != nil {
line, err = strconv.Atoi(description[i[0]+1 : i[1]-1])
if err != nil {
ERROR.Println("Failed to parse line number from error message:", err)
}
templateName = description[:i[0]]
if colon := strings.Index(templateName, ":"); colon != -1 {
templateName = templateName[colon+1:]
}
templateName = strings.TrimSpace(templateName)
description = description[i[1]+1:]
}
return templateName, line, description
}
// Return the Template with the given name. The name is the template's path
// relative to a template loader root.
//
// An Error is returned if there was any problem with any of the templates. (In
// this case, if a template is returned, it may still be usable.)
func (loader *TemplateLoader) Template(name string) (Template, error) {
// Case-insensitive matching of template file name
templateName := loader.templateNames[strings.ToLower(name)]
// Look up and return the template.
tmpl := loader.templateSet.Lookup(templateName)
// This is necessary.
// If a nil loader.compileError is returned directly, a caller testing against
// nil will get the wrong result. Something to do with casting *Error to error.
var err error
if loader.compileError != nil {
err = loader.compileError
}
if tmpl == nil && err == nil {
return nil, fmt.Errorf("Template %s not found.", name)
}
return GoTemplate{tmpl, loader}, err
}
// Adapter for Go Templates.
type GoTemplate struct {
*template.Template
loader *TemplateLoader
}
// return a 'revel.Template' from Go's template.
func (gotmpl GoTemplate) Render(wr io.Writer, arg interface{}) error {
return gotmpl.Execute(wr, arg)
}
func (gotmpl GoTemplate) Content() []string {
content, _ := ReadLines(gotmpl.loader.templatePaths[gotmpl.Name()])
return content
}
/////////////////////
// Template functions
/////////////////////
// Return a url capable of invoking a given controller method:
// "Application.ShowApp 123" => "/app/123"
func ReverseUrl(args ...interface{}) (template.URL, error) {
if len(args) == 0 {
return "", fmt.Errorf("no arguments provided to reverse route")
}
action := args[0].(string)
if action == "Root" {
return template.URL(AppRoot), nil
}
actionSplit := strings.Split(action, ".")
if len(actionSplit) != 2 {
return "", fmt.Errorf("reversing '%s', expected 'Controller.Action'", action)
}
// Look up the types.
var c Controller
if err := c.SetAction(actionSplit[0], actionSplit[1]); err != nil {
return "", fmt.Errorf("reversing %s: %s", action, err)
}
if len(c.MethodType.Args) < len(args)-1 {
return "", fmt.Errorf("reversing %s: route defines %d args, but received %d",
action, len(c.MethodType.Args), len(args)-1)
}
// Unbind the arguments.
argsByName := make(map[string]string)
for i, argValue := range args[1:] {
Unbind(argsByName, c.MethodType.Args[i].Name, argValue)
}
return template.URL(MainRouter.Reverse(args[0].(string), argsByName).Url), nil
}
func Slug(text string) string {
separator := "-"
text = strings.ToLower(text)
text = invalidSlugPattern.ReplaceAllString(text, "")
text = whiteSpacePattern.ReplaceAllString(text, separator)
text = strings.Trim(text, separator)
return text
}