Sonntag, 17. Mai 2015

Use HAML for Rails templates!

Ruby On Rails ships with ERB as templating system. It is simple and high generalized. Its flexibility is also its severest drawback.
A more suitable HTML templating system would:
  1. be tightly focused on generating HTML pages
  2. demand correct intendation
  3. reduce HTML tag verbosity and therefore increase readability
HAML is such a templating system and very common in the Ruby framework world.
It is easy to integrate by adding:
gem 'haml'
to the Gemfile.
A simple user.html.erb file:
<h1>Welcome <%= %></h1>
<div id="friends">
  <% @user.friends.each do |friend| %>
    <div id="<%= dom_id friend %>" class="friend">
      <%= %>
  <% end %>
can refactored by creating the user.html.haml containing:
  - @user.friends.each do |friend|
    .friend{ id: dom_id(friend) }=
The result is way shorter. HAML is well documented.
Please note that HAML forces you to take care of correct indentation. Otherwise it might crash with errors like:
Inconsistent indentation: 6 spaces used for indentation, 
but the rest of the document was indented using 4 spaces.
when there is a indent missing.
Or a little less intuitive:
SyntaxError - syntax error, unexpected keyword_ensure, 
expecting keyword_end
when indenting a Ruby block (like an interator) was incorrect.
Or even harder to get is unintentional DOM structure by wrong indentation.
Anyway HAML forces to indent correctly because whitespaces matter. And that is a benefit, because it helps to write cleaner HTML.
Further articles of interest:

Supported by Ruby 2.1.1 and Ruby on Rails 4.1.8