Ruby on Rails Views HAML - an alternative way to use in your views


Example

HAML (HTML abstraction markup language) is a beautiful and elegant way to describe and design the HTML of your views. Instead of opening- and closing tags, HAML uses indentation for the structure of your pages. Basically, if something should be placed within another element, you just indent it by using one tab stop. Tabs and white space are important in HAML, so be sure that you always use the same amount of tabs.

Examples:

#myview.html.erb
<h1><%= @the_title %></h1>
<p>This is my form</p>
<%= render "form" %>

And in HAML:

#myview.html.haml
%h1= @the_title
%p
    This is my form
= render 'form'

You see, the structure of the layout is much clearer than using HTML and ERB.

Installation

Just install the gem using

gem install haml

and add the gem to the Gemfile

gem "haml"

For using HAML instead of HTML/ERB, just replace the file extensions of your views from something.html.erb to something.html.haml.

Quick tipps

Common elements like divs can be written in a short way

HTML

<div class="myclass">My Text</div>

HAML

%div.myclass

HAML, shorthand

.myclass

Attributes

HTML

<p class="myclass" id="myid">My paragraph</p>

HAML

%p{:class => "myclass", :id => "myid"} My paragraph

Inserting ruby code

You can insert ruby code with the = and - signs.

= link_to "Home", home_path

Code starting with = will be executed and embedded into the document.

Code starting with - will be executed, but not inserted into the document.

Full documentation

HAML is very easy to start with, but is also very complex, so that I'll recommend reading the documentation.