Asitha Bandara's picture

Haml and Rails Are a Match Made in Heaven – Here’s Why


Before I tell you why Haml is so good with Rails, let me say something about ERB - the default template system for Rails.

We embed Ruby into HTML using ERB just like we do in ASP, JSP and PHP. For example, this is how we embed Ruby in an html.erb file:


As you can see in the code segment, I created a basic form in Rails using a table layout.

I used this delimiter to embed Ruby within the HTML file:

<% %>
<%= %>

It really annoys me when there is a huge code in an ERB file, so I started using Haml instead.


Haml is a popular alternative to ERB, and a really good one at that. Haml will eliminate repetitive tags in HTML and ultimately give me a beautiful code that is easy to read.


Indentation is the key with Haml, and it makes for a well-structured code. True, Rails giving you indentation errors can put you off, but it won’t happen – at least not often – if you are careful.

This is the above ERB code, but using Haml:


I think you can clearly see the difference just by glancing at the code.

Now you see why I like using Haml! Plus, it is super easy to handle my view files in Rails now. Besides readability, you have to commend it for cleanliness and production speed.

For more information check out this link:


This Is How I Add Haml into a Project

1. First add the GEM file.

Click here to read about Haml

gem 'haml', '~> 4.0', '>= 4.0.7'


gem install haml -v 4.0.7


2. Do a bundle install:

$bundle install


3. Done!

Now anytime you create a controller after bundle install Rails will generate view in the format for Haml.

Move from HTML to Haml

After adding Haml I had an issue. I couldn’t figure out how to convert my existing html.erb to html.haml. Then I discovered this platform that does the job:

Convert HTML to Haml

Pretty easy!

If you need to convert the whole ERB project to a Haml project, you can use a Shell script, but please note that this is something I haven’t done yet. Here’s more info on it:

Is there a bash command for converting an entire directory to HAML from HTML?

for file in $(find . -type f -name \*.html.erb); do
html2haml -e ${file} "$(dirname ${file})/$(basename ${file} .erb).haml";


or use this gem to convert:



Here are some basics:

. ----> for class
# ----> for id
% ----> for tags
- ----> ruby
= ----> output in ruby


And here are some examples, so you can get a better idea:





When we add attributes into tags





If you want to add div with a class “content”

Anything inside the div


The same thing with an ID

Anything inside the div






So consider using Haml next time… Actually, start today! :)


Comments (0)

Leave a comment