Search code examples
javascripthtmlcheckboxbooleanpug

Checkbox checked attribute not working with Pug


I have the following checkbox written in Pug:

 input(id="favorite" type="checkbox" name="favorite" value='true' checked='#{item.favorite ? true : false}')

When I inspect the item I can see that the logic for the checked attribute is working, showing true or false depending on the situation, but no matter if it is true or false, the checkbox is always selected.

I think the issue might be that, because of #{item.favorite ? true : false} is between quotes, the result is not being treated as boolean but as a string. But if I write the code with out quotes it does not work.

My question is, how should I write this so the checked attribute reads the result as boolean?


Solution

  • As outlined in the manual section about attributes this can be achieved by

    input(checked=item.favorite id="favorite" type="checkbox" name="favorite" value="true")
    

    If item.favorite is a falsey value, checked is omitted.