Conditional HTML tag attribute in HAML
Let's say we want to add a class to a row in a table if a condition is given:
%tr{ row.name == "active" ? {class: "active"} : {}}
If the condition is true, the attribute class="active"
will be added to the tr
tag, otherwise nothing will be added.
It's that easy, but I had a hard time finding out the first time.
Written by Fernando Briano
Related protips
6 Responses
I was just looking how to do this, thanks!
Glad it helped. I t helps me every time I need to do this. I'll memorize it eventually... :P
Great tip. Thanks!
I didn't know you could pass a Hash directly inside the brackets.
Thanks!
Or you could do this like
%tr{class: ("active" if row.name == "active")}
That way you could also have other attributes besides the class
@zinkkrysty
I was thinking the same as you before, but when you need several conditional attributes, it will get messy, like this:
%tr{ class: ("active" if row.name == "active"), title: ("active" if row.name == "active"), data-id = #{row.id} }
instead you can write it like this
%tr{ {data-id = #{row.id}}, row.name == "active" ? { class: "active", title: "active" } : { } }
unconditional attributes can be placed into different hash, and the two hashes will be flatten by haml, I think. And sorry that I don't know how to beautify my code in a block :D