diff --git a/content_helper.go b/content_helper.go index f23f3dd..7d72bed 100644 --- a/content_helper.go +++ b/content_helper.go @@ -38,7 +38,20 @@ func contentForHelper(name string, help HelperContext) { 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 { - return template.HTML(""), errors.WithStack(errors.New("missing contentOf block: " + name)) + 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) } diff --git a/content_helper_test.go b/content_helper_test.go index 7301ec5..f9702d5 100644 --- a/content_helper_test.go +++ b/content_helper_test.go @@ -47,3 +47,33 @@ func Test_ContentForOf_MissingBlock(t *testing.T) { _, err := Render(input, NewContext()) r.EqualError(err, "line 2: missing contentOf block: buttons") } + +func Test_ContentForOf_MissingBlock_DefaultBlock(t *testing.T) { + r := require.New(t) + input := ` + <%= contentOf("my-block") { %>default<% } %> + ` + s, err := Render(input, NewContext()) + r.NoError(err) + r.Contains(s, "default") +} + +func Test_ContentForOf_MissingBlock_NoBlockContent(t *testing.T) { + r := require.New(t) + input := ` + <%= contentOf("buttons") %> + ` + _, err := Render(input, NewContext()) + r.EqualError(err, "line 2: missing contentOf block: buttons") +} + +func Test_ContentForOf_DefaultBlock(t *testing.T) { + r := require.New(t) + input := ` + <% contentFor("buttons") { %>custom<% } %> + <%= contentOf("buttons") { %>default<% } %> + ` + s, err := Render(input, NewContext()) + r.NoError(err) + r.Contains(s, "custom") +}