-
Notifications
You must be signed in to change notification settings - Fork 3
/
plush.go
80 lines (70 loc) · 1.71 KB
/
plush.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
package template
import (
"html"
"io"
"strings"
"sync"
"github.com/gobuffalo/plush"
"github.com/pkg/errors"
)
type plushTemplate struct {
impl *plush.Template
}
var once sync.Once
// parsePlush parses a plush template in the source string.
func parsePlush(source string) (Template, error) {
once.Do(prepHelpers)
kt, err := plush.Parse(source)
if err != nil {
return nil, err
}
return plushTemplate{impl: kt}, nil
}
// Render writes the result of rendering the plush template using the provided scope to the IO writer.
func (t plushTemplate) Render(out io.Writer, scope Scope) error {
result, err := t.RenderString(scope)
if err != nil {
return err
}
result = html.UnescapeString(result)
_, err = out.Write([]byte(result)) // Makes copy of result.
return err
}
// Render returns the result of rendering the plush template using the provided scope.
func (t plushTemplate) RenderString(scope Scope) (string, error) {
context := plush.NewContext()
for k, v := range scope {
ks, ok := k.(string)
if !ok {
return "", errors.Errorf("Internal error: Expected all scope keys to be strings, unexpected: %v", k)
}
context.Set(ks, v)
}
return t.impl.Exec(context)
}
func prepHelpers() {
// Support the following plush helpers:
whitelist := []string{
"markdown", // Markdown
"len", // Len
"range", // Range
"between", // Between
"until", // Until
"inspect", // Inspect
}
helpers, _ := plush.NewHelperMap()
for k, v := range plush.Helpers.Helpers() {
if contains(whitelist, k) {
helpers.Helpers()[strings.Title(k)] = v
}
}
plush.Helpers = helpers
}
func contains(strs []string, str string) bool {
for _, s := range strs {
if s == str {
return true
}
}
return false
}