Image
#rails
Posted April 19, 2021 ‐  2 min read

ERB vs HAML

This is an opinionated article about ERB and HAML with Rails. Let's compare each other and pick a winner.

Use case

In the Ruby-on-Rails word, they are known as templating languages. In the MVC concept, they represent "the View". Both are here to output HTML.

Example

Examples worth a thousand words, so here are two examples, one with ERB, the other with HAML. Both are strictly equivalent. I tried to put different kinds of concepts in order to highlight various problems : create variables, run ruby code, inline style, condition, loop, etc.

ERB template file

<% v = run_some_ruby_code %>

<div id="main" style="margin-left: 0">

  <div class="left column">
    <h2>Welcome to the library</h2>

    <% books.each_with_index do |book, indx| %>
      <% if indx > 0 %>
        <p><%= book.title %></p>
      <% end %>
    <% end %>
  </div>


  <div class="right column">
    <%= render "shared/sidebar" %>
  </div>

</div>

Is equivalent to this HAML template file :

- v = run_some_ruby_code
#main{style: "margin-left: 0"}
  .left.column
    %h2 Welcome to the library
    - books.each_with_index do |book, indx|
      - if indx > 0
        %p= book.title
  .right.column
    = render "shared/sidebar"

ERB

HAML

And the winner is

ERB.

I've used both and I have to say HAML has one very big advantage : a lot less verbosity. This is very handy for large template files. But large template files are not so frequent in an application if you properly cut them into small pieces - partial or view_components.

So now HAML big one advantage doesn't outreach the sum of its disadvantages : hard to copy/paste from examples, and tricky corner cases notably.

Help needed 😊

If you enjoyed the article, you can :

  • Share the article on Twitter , or LinkedIn , or Reddit , it will stimulate the writing effort, thanks !
  • Subscribe to the newsletter, you'll be warned each time a new Rails tutorial is released : we start from the rails new command to fully understand a new concept.
  • Subscribe to the Bootrails Beta, it's a tool to launch new Rails apps.

Thanks to all,

David