This repository has been archived by the owner on Jul 7, 2020. It is now read-only.
forked from gobuffalo/buffalo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
template_helpers.go
100 lines (79 loc) · 1.89 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
98
99
100
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.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"] = func(file string) (string, error) {
return s.assetPath(file)
}
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()
}