Skip to content

Commit

Permalink
empty string is truthy fixes #24
Browse files Browse the repository at this point in the history
  • Loading branch information
markbates committed Dec 22, 2017
1 parent 6258824 commit f03aba1
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 3 deletions.
10 changes: 8 additions & 2 deletions compiler.go
Original file line number Diff line number Diff line change
Expand Up @@ -167,9 +167,15 @@ func (c *compiler) isTruthy(i interface{}) bool {
if i == nil {
return false
}
if b, ok := i.(bool); ok {
return b
switch t := i.(type) {
case bool:
return t
case string:
return t != ""
case template.HTML:
return t != ""
}

return true
}

Expand Down
19 changes: 18 additions & 1 deletion if_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -128,8 +128,25 @@ func Test_Render_If_Else_True(t *testing.T) {

func Test_Render_If_Matches(t *testing.T) {
r := require.New(t)
input := `<p><%= if ("foo" ~= "bar") { return "hi"} else { return "bye"} %></p>`
input := `<p><%= if ("foo" ~= "bar") { return "hi" } else { return "bye" } %></p>`
s, err := Render(input, NewContext())
r.NoError(err)
r.Equal("<p>bye</p>", s)
}

func Test_If_String_Truthy(t *testing.T) {
r := require.New(t)

ctx := NewContext()
ctx.Set("username", "")

input := `<p><%= if (username && username != "") { return "hi" } else { return "bye" } %></p>`
s, err := Render(input, ctx)
r.NoError(err)
r.Equal("<p>bye</p>", s)

ctx.Set("username", "foo")
s, err = Render(input, ctx)
r.NoError(err)
r.Equal("<p>hi</p>", s)
}

0 comments on commit f03aba1

Please sign in to comment.