Haml

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:

%tag.class#id
%tag{attribute: value}
%self_closing_tag/

– Ruby (doesn’t render anything)
= Ruby (renders something)
#{inline_ruby}

/ Comment

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:

<h1>Sign Up</h1>
<br />

<p>
<div id=”signup”>
<%= form_for @user do |f| %>
<%= f.label :email %>
<%= f.text_field :email %>
<br />

<%= f.label :password %>
<%= f.password_field :password %>
<br />

<%= f.submit “Sign Up”, class: “btn” %>
<% end %>
</div>
</p>

Now let’s see it in Haml:

%h1.page-title
Sign Up
%br/

%p
#signup
– form_for @user do |f|
= f.label :email
= f.text_field :email
%br/

= f.label :password
= f.password_field :password
%br/

= 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/.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s