Skip to content
Daniel Kehoe edited this page May 30, 2011 · 19 revisions

Using Haml with Rails

This is a guide for developers using the example apps from the Rails Apps repository. Others may find it helpful as well.

If you are creating an application template, this step uses the haml recipe from the rails_apps_composer repository.

Background

Haml is a popular alternative to the default Rails templating language (“ERB”).

ERB is a templating system that embeds Ruby into an HTML document, similar to ASP, JSP and PHP. It preserves the syntax of HTML and allows Ruby code to be embedded within a pair of <% and %> delimiters.

Haml is intended for “elegant” markup, elminating the repetitive tags of HTML and integrating conditional logic succinctly. It’s easier to read.

Indentation is significant in Haml, which makes for well-structured code, but errors in nesting can be an challenging aspect of using Haml.

Setting Up Haml

Here are instructions for adding Haml to Rails.

The example apps from the Rails Apps repository use the default “ERB” Rails template engine. Optionally, you can use another template engine, such as Haml. You’ll need extra gems in the Gemfile for Haml:

gem 'haml', '>= 3.1.1'
gem 'haml-rails', '>= 0.3.4', :group => :development

Run the gem bundler command:

$ bundle install

With the haml-rails gem, there is no need to modify the application.rb file to accommodate Haml. Any time you generate a controller or scaffold, you’ll get Haml instead of ERB templates. And when your Rails application loads, Haml will be loaded and initialized.

Haml Tools

Most Rails example code and tutorials use ERB. But it’s very easy to convert ERB to Haml using the Html2Haml website. Paste your HTML or ERB code into a text field, click convert, and you’ll have clean Haml code, ready to paste in your app views.

Clone this wiki locally