forked from gobuffalo/plush
-
Notifications
You must be signed in to change notification settings - Fork 0
/
content_helper.go
57 lines (51 loc) · 1.47 KB
/
content_helper.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
package plush
import (
"html/template"
"github.com/pkg/errors"
)
// ContentFor stores a block of templating code to be re-used later in the template
// via the contentOf helper.
// An optional map of values can be passed to contentOf,
// which are made available to the contentFor block.
/*
<% contentFor("buttons") { %>
<button>hi</button>
<% } %>
*/
func contentForHelper(name string, help HelperContext) {
help.Set("contentFor:"+name, func(data map[string]interface{}) (template.HTML, error) {
ctx := help.New()
for k, v := range data {
ctx.Set(k, v)
}
body, err := help.BlockWith(ctx)
if err != nil {
return "", errors.WithStack(err)
}
return template.HTML(body), nil
})
}
// ContentOf retrieves a stored block for templating and renders it.
// You can pass an optional map of fields that will be set.
/*
<%= contentOf("buttons") %>
<%= contentOf("buttons", {"label": "Click me"}) %>
*/
func contentOfHelper(name string, data map[string]interface{}, help HelperContext) (template.HTML, error) {
fn, ok := help.Value("contentFor:" + name).(func(data map[string]interface{}) (template.HTML, error))
if !ok {
if !help.HasBlock() {
return template.HTML(""), errors.WithStack(errors.New("missing contentOf block: " + name))
}
ctx := help.New()
for k, v := range data {
ctx.Set(k, v)
}
body, err := help.BlockWith(ctx)
if err != nil {
return template.HTML(""), errors.WithStack(err)
}
return template.HTML(body), nil
}
return fn(data)
}