forked from gobuffalo/buffalo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
template_helpers.go
93 lines (71 loc) · 1.74 KB
/
template_helpers.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
package render
import (
"encoding/json"
"html/template"
"path/filepath"
"sync"
"github.com/gobuffalo/tags"
"github.com/pkg/errors"
)
var assetsMutex = &sync.Mutex{}
var assetMap map[string]string
func loadManifest(manifest string) error {
assetsMutex.Lock()
defer assetsMutex.Unlock()
err := json.Unmarshal([]byte(manifest), &assetMap)
return err
}
func assetPathFor(file string) string {
assetsMutex.Lock()
defer assetsMutex.Unlock()
filePath := assetMap[file]
if filePath == "" {
filePath = file
}
return filepath.Join("/assets", filePath)
}
func (s templateRenderer) addAssetsHelpers(helpers Helpers) Helpers {
helpers["assetPath"] = func(file string) (string, error) {
return s.assetPath(file)
}
helpers["javascriptTag"] = func(file string, options tags.Options) (template.HTML, error) {
h, err := s.assetPath(file)
if err != nil {
return "", errors.WithStack(err)
}
return jsTag(h, options), nil
}
helpers["stylesheetTag"] = func(file string, options tags.Options) (template.HTML, error) {
h, err := s.assetPath(file)
if err != nil {
return "", errors.WithStack(err)
}
return cssTag(h, options), nil
}
return helpers
}
func jsTag(src string, options tags.Options) template.HTML {
if options == nil {
options = tags.Options{}
}
if options["type"] == nil {
options["type"] = "text/javascript"
}
options["src"] = src
jsTag := tags.New("script", options)
return jsTag.HTML()
}
func cssTag(href string, options tags.Options) template.HTML {
if options == nil {
options = tags.Options{}
}
if options["rel"] == nil {
options["rel"] = "stylesheet"
}
if options["media"] == nil {
options["media"] = "screen"
}
options["href"] = href
cssTag := tags.New("link", options)
return cssTag.HTML()
}