forked from gobuffalo/buffalo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
helpers.go
61 lines (54 loc) · 1.34 KB
/
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
package helpers
import (
"encoding/json"
"html/template"
"strings"
"github.com/aymerick/raymond"
"github.com/markbates/inflect"
)
// Helpers that are automatically injected into templates.
var Helpers = map[string]interface{}{
"js_escape": template.JSEscapeString,
"html_escape": template.HTMLEscapeString,
"json": ToJSON,
"content_for": ContentFor,
"content_of": ContentOf,
"upcase": strings.ToUpper,
"downcase": strings.ToLower,
}
func init() {
for k, v := range inflect.Helpers {
Helpers[k] = v
}
}
// ToJSON converts an interface into a string.
func ToJSON(v interface{}) string {
b, err := json.Marshal(v)
if err != nil {
return err.Error()
}
return string(b)
}
// ContentFor stores a block of templating code to be re-used later in the template.
/*
{{content_for "buttons"}}
<button>hi</button>
{{/content_for}}
*/
func ContentFor(name string, options *raymond.Options) string {
ctx := options.Ctx().(map[string]interface{})
body := options.Fn()
ctx[name] = raymond.SafeString(body)
return ""
}
// ContentOf retrieves a stored block for templating and renders it.
/*
{{content_of "buttons"}}
*/
func ContentOf(name string, options *raymond.Options) raymond.SafeString {
ctx := options.Ctx().(map[string]interface{})
if s, ok := ctx[name]; ok {
return s.(raymond.SafeString)
}
return raymond.SafeString("")
}