slim-template / slim

Slim is a template language whose goal is to reduce the syntax to the essential parts without becoming cryptic.
https://slim-template.github.io
MIT License
5.3k stars 501 forks source link

Better way to handle boolean attributes? #929

Closed techdude closed 1 year ago

techdude commented 1 year ago

Is there a cleaner/better way to include or not include boolean attributes based on a ruby variable? I came up with the following solution for setting the default value of a checkbox, but it's surprising that there isn't a way to do this without relying on the generic splat operator and a separate helper. Especially for such a common language feature.

Helper:

def checked(val)
    val ? { 'checked': 'checked' } : {}
 end

Template file: input#foo (type="checkbox" *checked(foo))

minad commented 1 year ago

If foo is a boolean variable, you can write input checked=foo and it should create an appropriate attribute. If foo is not a boolean and you want to generate the attribute based on "truthiness", write input checked=(foo and true). Does this work for you?