How HAML changed my (XHTML) life
Using HAML and SASS have streamlined my template and XHTML building in a way I couldn’t imagine. I’ve tried some markup/markdown like textile but HAML is so well integrated into Ruby on Rails, it’s plain amazing. Come on, take a look, I promise you will like that one ![]()
But what is HAML?
HAML (HTML Abstract Markup Language) is a markup language that changes the way you write XHTML. Let me give you a small example:
<html>
<head>
<title>a test</title>
<link rel="stylesheet" type="text/css" href="style.css"/>
</head>
<body>
<div id="header"><h1>some headline</h1></div>
<div id="menu">link1 link2 link3</div>
<div id="content">
<p>some text in a paragraph</p>
</div>
</body>
</html>
This is standard XHTML code (OK quick and dirty). With HAML, you can shorten that to
!!!
%html
%head
%title a test
%style{:type => "text/css", :href => "style.css"}/
%body
#header
%h1 some headline
#menu link1 link2 link3
#content
%p some text in a paragraph
As you can see, there are no ending tags anymore, all the structuring is done via python-style indenting. This not only gives you a cleaner code but – once you are used to it – provides amazing speed and structure, especially when used in conjunction with Ruby code. The trick is you can add Ruby code directly into the {} and () of the XHTML tags. One more example which makes things a bit more clear (I hope):
<% for m in getMenuItems('mainMenu') %>
<% if m.is_active == false or m.is_active == "" %>
<% next %>
<% end %>
<%= link_to m.name.to_s, '/somecontroller/' + m.id.to_s %>
<% end %>
With HAML, it looks like:
- for m in getMenuItems('mainMenu')
- if m.is_active == false or m.is_active == ""
- next
= link_to m.name.to_s, '/somecontroller/' + m.id.to_s
As this is just a very basic loop with only one condition and no surrounding XHTML stuff I can only show you how HAML makes the code readable and shortens it (since you don’t need those pesky <% end %> statements anymore, once you utilize it in your layouts and views you will see how powerful it is.
OK, how can I get it to run with my Rails app?
Just install the gem via
sudo gem install haml
and add
config.gem 'haml'
to your config/environment.rb. Then install and unpack the gem with
rake gems:install
rake gems:unpack
and you’re set. Now you need to rename the desired views from .html.erb to .html.haml (e.g. app/views/layouts/application.html.haml) and start changing the code from ERBish style to HAML. Try it! Take a view file, rename it and start changing it to HAML and you will see how cool it is once you have worked with it.
Be sure to check out the documentation @ http://haml-lang.com/ it is very useful and the tutorials on the official site are too!
