This repository has been archived by the owner on Dec 9, 2020. It is now read-only.
forked from gobuffalo/plush
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplush.go
103 lines (87 loc) · 2.17 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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package plush
import (
"fmt"
"html/template"
"io"
"io/ioutil"
"sync"
"github.com/gobuffalo/helpers/hctx"
)
// DefaultTimeFormat is the default way of formatting a time.Time type.
// This a **GLOBAL** variable, so if you change it, it will change for
// templates rendered through the `plush` package. If you want to set a
// specific time format for a particular call to `Render` you can set
// the `TIME_FORMAT` in the context.
//
/*
ctx.Set("TIME_FORMAT", "2006-02-Jan")
s, err = Render(input, ctx)
*/
var DefaultTimeFormat = "January 02, 2006 15:04:05 -0700"
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, err
}
return t, nil
}
// Render a string using the given the context.
func Render(input string, ctx hctx.Context) (string, error) {
t, err := Parse(input)
if err != nil {
return "", err
}
return t.Exec(ctx)
}
func RenderR(input io.Reader, ctx hctx.Context) (string, error) {
b, err := ioutil.ReadAll(input)
if err != nil {
return "", err
}
return Render(string(b), ctx)
}
// RunScript allows for "pure" plush scripts to be executed.
func RunScript(input string, ctx hctx.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
}