Last Updated: April 07, 2016
·
15.18K
· picandocodigo

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.

6 Responses
Add your response

I was just looking how to do this, thanks!

over 1 year ago ·

Glad it helped. I t helps me every time I need to do this. I'll memorize it eventually... :P

over 1 year ago ·

Great tip. Thanks!

over 1 year ago ·

I didn't know you could pass a Hash directly inside the brackets.
Thanks!

over 1 year ago ·

Or you could do this like

%tr{class: ("active" if row.name == "active")}

That way you could also have other attributes besides the class

over 1 year ago ·

@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

over 1 year ago ·