Using Haml with Rails

I. Introduction:

Haml is an useful tool to keep the work clean and organized. That why today, I want to introduce how to use Haml in a new Rails project and how to integrate into an existing project.

II. Installation:

Add gems "haml-rails" and run bundle install


gem "haml-rails"

Convert the erb layout file by running this command:

rails generate haml:application_layout convert

You can also converting all .erb views to haml by:

rake haml:erb2haml

Beside converting .erb file, this command will give you option to replace existing haml file or keep it in place.

III. Using Haml:

Here some example to show how Haml help to simplify your markup and speed up front-end development:

1. Tags:


<h1>Welcome To The Show</h1>


%h1= "Welcome To The Show"

By using % at the beginning, folloewd by the tag's name, you'll never have to close the tag again

2. Loops:


<% @notes.each do |note| %>
    <h2><%= note.title %></h2>
    <p><%= note.content %></p>
<% end %>


  • @notes.each do |note| %h2= note.title %p= note.content

For ruby code, you just have to put = and don't need <% end %> blocks to close

3. Divs

You don't even need to write the name's tag div but just use the %, and Haml will do the rest.


<div class="header">
    <div class="wrapper">
        <%= @course.teacher %>


        = @course.teacher

4. Adding attributes:

We already have some attributes examples, but I will write it more clearly. You can define in the the similiar way with CSS


<section class=”container”>
  <h1><%= post.title %></h1>
  <h2><%= post.subtitle %></h2>
  <div class=”content”, id="post_content">
    <%= post.content %>


  %h1= post.title
  %h2= post.subtitle
    = post.content

IV. Conclusion

Haml can be pretty hard at the beginning when you close to it, you'll find it efficiency.

All Rights Reserved