This repository has been archived by the owner on Feb 24, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 577
/
template_helpers.go
97 lines (77 loc) · 1.83 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
94
95
96
97
package render
import (
"encoding/json"
"html/template"
"path/filepath"
"sync"
"github.com/gobuffalo/tags"
"github.com/pkg/errors"
)
var assetsMutex = &sync.RWMutex{}
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.RLock()
filePath := assetMap[file]
assetsMutex.RUnlock()
if filePath == "" {
filePath = file
}
return filepath.ToSlash(filepath.Join("/assets", filePath))
}
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", jsTag},
{"stylesheetTag", cssTag},
{"imgTag", imgTag},
}
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 "", errors.WithStack(err)
}
return h.fn(f, options), nil
}
}(h)
}
return helpers
}
func jsTag(src string, options tags.Options) template.HTML {
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["rel"] == nil {
options["rel"] = "stylesheet"
}
if options["media"] == nil {
options["media"] = "screen"
}
options["href"] = href
cssTag := tags.New("link", options)
return cssTag.HTML()
}
func imgTag(src string, options tags.Options) template.HTML {
options["src"] = src
imgTag := tags.New("img", options)
return imgTag.HTML()
}