-
Notifications
You must be signed in to change notification settings - Fork 56
/
template.go
73 lines (60 loc) · 1.37 KB
/
template.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
package plush
import (
"github.com/gobuffalo/plush/v5/ast"
"github.com/gobuffalo/plush/v5/helpers/hctx"
"github.com/gobuffalo/plush/v5/parser"
)
// Template represents an input and helpers to be used
// to evaluate and render the input.
type Template struct {
Input string
program *ast.Program
}
// NewTemplate from the input string. Adds all of the
// global helper functions from "Helpers", this function does not
// cache the template.
func NewTemplate(input string) (*Template, error) {
t := &Template{
Input: input,
}
err := t.Parse()
if err != nil {
return t, err
}
return t, nil
}
// Parse the template this can be called many times
// as a successful result is cached and is used on subsequent
// uses.
func (t *Template) Parse() error {
if t.program != nil {
return nil
}
program, err := parser.Parse(t.Input)
if err != nil {
return err
}
t.program = program
return nil
}
// Exec the template using the content and return the results
func (t *Template) Exec(ctx hctx.Context) (string, error) {
err := t.Parse()
if err != nil {
return "", err
}
ev := compiler{
ctx: ctx,
program: t.program,
}
s, err := ev.compile()
return s, err
}
// Clone a template. This is useful for defining helpers on per "instance" of the template.
func (t *Template) Clone() *Template {
t2 := &Template{
Input: t.Input,
program: t.program,
}
return t2
}