-
Notifications
You must be signed in to change notification settings - Fork 0
/
render_container_test.go
74 lines (60 loc) · 1.7 KB
/
render_container_test.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
package veun_test
import (
"context"
"html/template"
"testing"
"github.com/alecthomas/assert/v2"
. "github.com/stanistan/veun"
t "github.com/stanistan/veun/template"
)
type ContainerView struct {
Heading, Body AsView
}
var containerViewTpl = t.MustParse("containerView", `<div>
<div class="heading">{{ slot "heading" }}</div>
<div class="body">{{ slot "body" }}</div>
</div>`)
func tplWithRealSlotFunc(ctx context.Context, tpl *template.Template, slots map[string]AsView) *template.Template {
return tpl.Funcs(template.FuncMap{
"slot": func(name string) (template.HTML, error) {
slot, ok := slots[name]
if ok {
return Render(ctx, slot)
}
return template.HTML(""), nil
},
})
}
func (v ContainerView) AsHTML(ctx context.Context) (template.HTML, error) {
return t.HTMLTemplate{
Tpl: tplWithRealSlotFunc(ctx, containerViewTpl, map[string]AsView{
"heading": v.Heading,
"body": v.Body,
}),
}.AsHTML(ctx)
}
func (v ContainerView) View(_ context.Context) (*View, error) {
return V(v), nil
}
var childViewTemplate = template.Must(
template.New("childView").Parse(`{{ . }}`),
)
type ChildView1 struct{}
func (v ChildView1) View(_ context.Context) (*View, error) {
return V(t.Template{Tpl: childViewTemplate, Data: "HEADING"}), nil
}
type ChildView2 struct{}
func (v ChildView2) View(_ context.Context) (*View, error) {
return V(t.Template{Tpl: childViewTemplate, Data: "BODY"}), nil
}
func TestRenderContainer(t *testing.T) {
html, err := Render(context.Background(), &ContainerView{
Heading: ChildView1{},
Body: ChildView2{},
})
assert.NoError(t, err)
assert.Equal(t, template.HTML(`<div>
<div class="heading">HEADING</div>
<div class="body">BODY</div>
</div>`), html)
}