Using Haml Views

20 Jun 2011

Haml is a markup language that’s used to cleanly and simply describe the HTML of any web document without the use of inline code. Haml functions as a replacement for inline page templating systems such as PHP, ASP, and ERB, the templating language used in most Ruby on Rails applications. However, Haml avoids the need for explicitly coding HTML into the template, because it itself is a description of the HTML, with some code to generate dynamic content.

you can install haml in two ways

  1. install from rubygem repository
gem install haml
  1. install from source
git clone git://github.com/nex3/haml.git
cd haml
rake install

If you prefer installing via bundle, append this line in your Gemfile.

gem 'haml'
# if rails
gem 'haml-rails'

After adding this code to your Gemfile just run “bundle install”. Haml gem give us a full freedom to convert html or erb files to haml, for that you can use

html2haml "html_path"

To achive this we have to install two more dependent gems. i prefer you to use that gems in development mode if you are using bundler.

# If you are installing gem directly use the following
gem install hpricot
gem install ruby_parse

# Otherwise if you are using bundler add following lines to your Gemfile
group :developement do
  gem 'hpricot'
  gem 'ruby_parser'
end

Here is small code snippet which will help you to create a new haml from your erb files and delete the existing erb file in your rails application.

# Will create a new haml file from your existing erb file.
for i in `find app/views -name '*.erb'` ; do html2haml -e $i ${i%erb}haml ;  done

# Will delete your existing erb file.
for i in `find app/views/devise -name '*.erb'` ; do rm $i ; done