Archive for October 2009

Haml and Rails

Thursday, October 8, 2009 · Posted in

Haml is a markup language used to describe XHTML. Haml is very easy to read and enables developers to avoid explicitly coding XHTML into their templates.


To use Haml in rails follow the steps below.


Step 1.
Install the Haml RubyGem by the command
- gem install haml


Step 2.
Install the Haml Ruby on Rails plugin by
- haml --rails your-rails-app


Haml plugin installation can be skipped by alternately requiring the Haml RubyGem in your application.


Haml and Sass can be rendered from existing HTML or CSS. After installing the gem and the hpricot dependency, haml, sass, html2haml and css2sass commands are installed. This is helpful for learners who want to see it in action first.


=> Now you can convert html files to haml and vice versa.
To convert haml to html:
- haml index.haml > index.html


To convert html to haml:
- html2haml index.html > index.haml


Inside Rails
Haml is simple to use. To reproduce a XHTML tag, simply use %tag. Closing tags is not required and handled via indentation. Indentation must be 2 spaces.


%p hello  
produces
<p>hello</p>
and
%div#container
  %p hello


produces
<div id="container">
  <p>hello</p>
</div>




Div tags can be even more easily produced by simply using .class and #id for <div class=“class”> and <div id=“id”> respectively.


Some other useful tags of html in haml are:
%p
  Here's a link to
  %a{href => "http://google.com"} Google
  and here's one to
  %a{href => "http://yahoo.com"} Yahoo


Note that the start of a tag's content must be on a new indented line if there are nested tags otherwise Haml will throw an error. Also note that since a line that starts with a period has significance in Haml, we use a backslash to escape it.


Ruby Code
Haml uses equals (=) to insert the result of Ruby code into the XHTML. This is similar to the way ERb uses <%= %>.


For example to replace hello with the value of an instance variable called @message we would use:
#container
  %p= @message




But to say hello to the contents of @message use
#container
  %p= "Hello #{@message}"




To evaluate Ruby code, but not output it, use the hyphen, -.


-@users.each do |user|
  %p== Hello #{user}

Notice we did something different. Double equals (==) interpolates Ruby code similarly to the way a single equals interpolates Ruby string.

%p= "Hello #{@student}"
produces the same result as
%p== Hello #{@student}


Multiline statements in haml
Just end each line of the statement with a pipe | character.


e.g.
/ Uncomment this if you want this functionality |
    %p |
        %label(for="remember_me") |
            Remember me: |
        = check_box_tag 'remember_me' |

Powered by Blogger.