Mark Needham

Thoughts on Software Development

Ruby/Haml: Conditionally/Optionally setting an attribute/class

with 2 comments

One of the things that we want to do reasonably frequently is set an attribute (most often a class) on a HTML element depending on the value of a variable.

I always forget how to do this in Haml so I thought I better write it down so I’ll remember next time!

Let’s say we want to add a success class to a paragraph if the variable correct is true and not have any value if it’s false.

The following code does what we want:

- correct = true
%p{:class => (correct ? "success" : nil) }
  important text

This generates the following HTML is correct is true:

<p class="success">
  important text
</p>

And the following HTML if it’s false

<p>
  important text
</p>

To summarise, if we set an attribute to nil in Haml it just won’t be rendered at all which is exactly what we want in this situation.

Written by Mark Needham

March 2nd, 2013 at 11:22 pm

Posted in Ruby

Tagged with ,

  • http://www.facebook.com/amartinsn Alexandre Martins

    Will bookmark this one Mark. Thanks!

  • http://www.markhneedham.com/blog Mark Needham

    @facebook-753273456:disqus nice! I recently came across one of your clojure posts from 2009 where you explained how to import Java classes!

    P.S. Why is your profile photo Uday?!