Mark Needham

Thoughts on Software Development

Archive for the ‘haml’ tag

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 ,

Ruby/Haml: Maintaining white space/indentation in a <pre> tag

without comments

I’ve been writing a little web app in which I wanted to display cypher queries inside a <pre> tag which was then prettified using SyntaxHighlighter but I was having problems with how code on new lines was being displayed.

I had the following Haml code to display a query looking up Gareth Bale in a graph:

%pre{ :class => "brush: cypher; gutter: false; toolbar: false;"}
  START player = node:players('name:"Gareth Bale"') 
  RETURN player.name

When I rendered the page it looked like this:

Bale broken tiff

After a bit of googling I ended up on this Stack Overflow post which described the preserve helper which seems to do the job:

%pre{ :class => "brush: cypher; gutter: false; toolbar: false;"}
  = preserve do
    START player = node:players('name:"Gareth Bale"') 
    RETURN player.name

That part of the page now looks much better:

Bale fixed

Written by Mark Needham

March 2nd, 2013 at 10:19 pm

Posted in Ruby

Tagged with ,