In my Rails projects I use the Haml markup language over the stock ERB language as much as possible. The “markup haiku” that is Haml is much easier to write and maintain. It does have a few quirks, but overall my views have been cleaner and easier to read than the ERB equivalents.
The syntax is dead simple. No more unnecessary end tags or wrapping lines of Ruby in special ERB tags.
All you have to remember is:
– Ruby (doesn’t render anything)
= Ruby (renders something)
If you don’t specify the name of a tag it defaults to a div.
Let’s take a look at an example. Here’s a small page using ERB:
<%= form_for @user do |f| %>
<%= f.label :email %>
<%= f.text_field :email %>
<%= f.label :password %>
<%= f.password_field :password %>
<%= f.submit “Sign Up”, class: “btn” %>
<% end %>
Now let’s see it in Haml:
– form_for @user do |f|
= f.label :email
= f.text_field :email
= f.label :password
= f.password_field :password
= f.submit “Sign Up”, class: “btn”
All of the superfluous markup gone. The page has been stripped down to its bare essentials: the necessary tag information and content. The simplicity does come with a small cost, but if you can deal with Python you can deal with this.
To cut out the end tags Haml uses indentation to determine the location and nesting of tags. It isn’t much of a problem though. If you do make a mistake chances are you’ll see it immediately. The time saved on typing alone is enough to justify a quick mistake or two.
Haml also differs from ERB in the way it handles Ruby evaluation. In ERB there is a single tag for Ruby code. In Haml there are two, `=` and `-`. If the return value of a line of Ruby needs to be rendered (like a button) the `=` is used. If the return value does not need to be rendered (like a form or an if) the `-` is used. This one does take a bit of getting used to. Every language has its downside and I think this is Haml’s.
Although Haml has a few differences from ERB, the most profound is the simplicity of the language. It strips away all the waste to leave only what is needed, information about tags and the content of the page. Haml’s optimization for speed and clarity makes the language great for almost all web projects large and small.
You can find more information about Haml at http://haml-lang.com/.