Ruby, Web Applications

Haml, Sinatra and template variables

Haml advertises itself as offering a haiku for HTML; that might mean it is short, beautiful and expressive or it could mean it is enigmatic, unsatisfying and cryptic. After a period away I have forgotten how Ruby-centric Haml is. If you want to include parameters in a Haml template within Sinatra you need to bind a map to the parameter locals.

haml :index, :locals => {:hello => “World”}

The easiest way to then include the data within a tag seems to be to use Ruby string interpolation

%p= “Hello #{locals[:hello]}”

There may be more elegant ways to do this but it seems relatively idiomatic. It is just hard to adjust to after months working on very restrictive templating systems.

Standard

3 thoughts on “Haml, Sinatra and template variables

  1. Arno.Nyhm says:

    you can use it without the locals hash in haml:

    define it:
    haml :index, :locals => {:info_text => “World”}

    use it:

    %p= “Hello #{info_text}”

  2. @Arno.Nyhm – that appears to work only sometimes; I had to change it back to “#{locals[:name]}” in order to get it to work so I’d just avoid doing it the way you suggested.

  3. Thanks for this, though it didn’t work for me. What did was:

    set :haml, :locals => {:info_text => “World”}

    Then in haml, I could either quote it with #{} or just evaluate it like this:

    %p= info_text

    So if the variable is a whole paragraph, that works a bit better, I think.

Leave a comment