_jiytg
Last Updated: April 07, 2016
·
8.651K
· picandocodigo
49c5bd577a2d7ef0628c8ceb90b8c7ae

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.

Say Thanks
Respond

6 Responses
Add your response

11243
9b029fbe569b3af35c235aedb2420b7b

I was just looking how to do this, thanks!

over 1 year ago ·
11244
49c5bd577a2d7ef0628c8ceb90b8c7ae

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

over 1 year ago ·
14553
Bf9a49c89790c65e6685c00a6bd00882

Great tip. Thanks!

over 1 year ago ·
16432
3306d834d48ed979e2510cb49bc4b7f1

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

over 1 year ago ·
24562
B8f8f573e852c25d5750027fdb5ca38f

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 ·
24900
None

@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 ·