Skip to content

Commit

Permalink
Allow default block for contentOf (#61)
Browse files Browse the repository at this point in the history
  • Loading branch information
ruudk authored and markbates committed Jul 20, 2018
1 parent 2ec029f commit d4510ca
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 1 deletion.
15 changes: 14 additions & 1 deletion content_helper.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
30 changes: 30 additions & 0 deletions content_helper_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 := `
<b0><%= contentOf("my-block") { %>default<% } %></b0>
`
s, err := Render(input, NewContext())
r.NoError(err)
r.Contains(s, "<b0>default</b0>")
}

func Test_ContentForOf_MissingBlock_NoBlockContent(t *testing.T) {
r := require.New(t)
input := `
<b0><%= contentOf("buttons") %></b0>
`
_, 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 := `
<b0><% contentFor("buttons") { %>custom<% } %></b0>
<b0><%= contentOf("buttons") { %>default<% } %></b0>
`
s, err := Render(input, NewContext())
r.NoError(err)
r.Contains(s, "<b0>custom</b0>")
}

0 comments on commit d4510ca

Please sign in to comment.