forked from gobuffalo/buffalo
/
template_helpers.go
68 lines (57 loc) · 1.33 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
package render
import (
"encoding/json"
"html/template"
"io"
"path"
"path/filepath"
ht "github.com/gobuffalo/helpers/tags"
"github.com/gobuffalo/tags/v3"
)
type helperTag struct {
name string
fn func(string, tags.Options) template.HTML
}
func (s *templateRenderer) addAssetsHelpers(helpers Helpers) Helpers {
helpers["assetPath"] = s.assetPath
ah := []helperTag{
{"javascriptTag", ht.JS},
{"stylesheetTag", ht.CSS},
{"imgTag", ht.Img},
}
for _, h := range ah {
func(h helperTag) {
helpers[h.name] = func(file string, options tags.Options) (template.HTML, error) {
if options == nil {
options = tags.Options{}
}
f, err := s.assetPath(file)
if err != nil {
return "", err
}
return h.fn(f, options), nil
}
}(h)
}
return helpers
}
var assetMap = stringMap{}
func assetPathFor(file string) string {
filePath, ok := assetMap.Load(file)
if filePath == "" || !ok {
filePath = file
}
return path.Join("/assets", filePath)
}
func loadManifest(manifest io.Reader) error {
m := map[string]string{}
if err := json.NewDecoder(manifest).Decode(&m); err != nil {
return err
}
for k, v := range m {
// I don't think v has backslash but if so, correct them when
// creating the map instead using the value in `assetPathFor()`.
assetMap.Store(k, filepath.ToSlash(v))
}
return nil
}