forked from gobuffalo/plush
-
Notifications
You must be signed in to change notification settings - Fork 0
/
plush.go
81 lines (67 loc) · 1.56 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
81
package plush
import (
"fmt"
"html/template"
"sync"
"github.com/pkg/errors"
)
var cache = map[string]*Template{}
var moot = &sync.Mutex{}
// BuffaloRenderer implements the render.TemplateEngine interface allowing velvet to be used as a template engine
// for Buffalo
func BuffaloRenderer(input string, data map[string]interface{}, helpers map[string]interface{}) (string, error) {
t, err := Parse(input)
if err != nil {
return "", err
}
if helpers != nil {
for k, v := range helpers {
data[k] = v
}
}
return t.Exec(NewContextWith(data))
}
// Parse an input string and return a Template, and caches the parsed template.
func Parse(input string) (*Template, error) {
moot.Lock()
defer moot.Unlock()
if t, ok := cache[input]; ok {
return t, nil
}
t, err := NewTemplate(input)
if err == nil {
cache[input] = t
}
if err != nil {
return t, errors.WithStack(err)
}
return t, nil
}
// Render a string using the given the context.
func Render(input string, ctx *Context) (string, error) {
t, err := Parse(input)
if err != nil {
return "", errors.WithStack(err)
}
return t.Exec(ctx)
}
// RunScript allows for "pure" plush scripts to be executed.
func RunScript(input string, ctx *Context) error {
input = "<% " + input + "%>"
ctx = ctx.New()
ctx.Set("print", func(i interface{}) {
fmt.Print(i)
})
ctx.Set("println", func(i interface{}) {
fmt.Println(i)
})
_, err := Render(input, ctx)
return err
}
type interfaceable interface {
Interface() interface{}
}
// HTMLer generates HTML source
type HTMLer interface {
HTML() template.HTML
}