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 pathhelpers.go
85 lines (72 loc) · 2.16 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package plush
import (
"bytes"
"fmt"
"sync"
"github.com/gobuffalo/helpers"
"github.com/gobuffalo/helpers/forms"
"github.com/gobuffalo/helpers/forms/bootstrap"
"github.com/gobuffalo/helpers/hctx"
"github.com/gobuffalo/plush/ast"
"github.com/pkg/errors"
)
// Helpers contains all of the default helpers for
// These will be available to all templates. You should add
// any custom global helpers to this list.
var Helpers = HelperMap{
moot: &sync.Mutex{},
}
func init() {
Helpers.Add("partial", partialHelper)
Helpers.AddMany(helpers.ALL())
Helpers.Add(forms.FormKey, bootstrap.Form)
Helpers.Add(forms.FormForKey, bootstrap.FormFor)
Helpers.Add("form_for", bootstrap.FormFor)
}
var _ hctx.HelperContext = &HelperContext{}
// HelperContext is an optional last argument to helpers
// that provides the current context of the call, and access
// to an optional "block" of code that can be executed from
// within the helper.
type HelperContext struct {
hctx.Context
compiler *compiler
block *ast.BlockStatement
}
const helperContextKind = "HelperContext"
// Render a string with the current context
func (h HelperContext) Render(s string) (string, error) {
return Render(s, h.Context)
}
// HasBlock returns true if a block is associated with the helper function
func (h HelperContext) HasBlock() bool {
return h.block != nil
}
// Block executes the block of template associated with
// the helper, think the block inside of an "if" or "each"
// statement.
func (h HelperContext) Block() (string, error) {
return h.BlockWith(h.Context)
}
// BlockWith executes the block of template associated with
// the helper, think the block inside of an "if" or "each"
// statement, but with it's own context.
func (h HelperContext) BlockWith(hc hctx.Context) (string, error) {
ctx, ok := hc.(*Context)
if !ok {
return "", fmt.Errorf("expected *Context, got %T", hc)
}
octx := h.compiler.ctx
defer func() { h.compiler.ctx = octx }()
h.compiler.ctx = ctx
if h.block == nil {
return "", errors.New("no block defined")
}
i, err := h.compiler.evalBlockStatement(h.block)
if err != nil {
return "", err
}
bb := &bytes.Buffer{}
h.compiler.write(bb, i)
return bb.String(), nil
}