Jump To Content
Merb

Merb


Using Haml

An introduction to haml

haml is template languages for Ruby on Rails. It’s a plugin that provides an alternative to Rails’ native view templating library erb. sass is included with haml, and provides templating for css files. Through clever usage of whitespace, both remove much of the verbosity of html and css (<>, end tags ,etc) , providing a concise way of creating templates. For example, take this typical layout template:


<!DOCTYPE html PUBLIC ”-//W3C//DTD XHTML 1.0 Transitional//EN”
 ”http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>

<html xmlns=”http://www.w3.org/1999/xhtml” xml:lang=”en” lang=”en”>
<head>
 <meta http-equiv=”content-type” content=”text/html;charset=UTF-8” />
 <title><%= controller.action_name %></title>
 <%= stylesheet_link_tag ‘mycss’ %>
</head>
  <body>
   <p style=”color: green”>
     <%= flash[:notice] %>
   </p>
   <div id=”header”>
     <h1>Header</h1>
   </div>
   <div id=”content”>
     <%= yield %>
   </div>
  </body>
</html>

Here’s the same thing in haml. Notice the usage of whitespace to delimit block the nesting of the code. Also, regular html can be mixed in as well.


!!!
%html{:xmlns => “http://www.w3.org/1999/xhtml”, “xml:lang” => “en”, :lang => “en”}
  %head
    <meta http-equiv=”content-type” content=”text/html;charset=UTF-8” />
    %title= controller.action_name
    = stylesheet_link_tag ‘mycss’
  %body
    %p{:style => “color:green”}= flash[:notice]
    #header
      %h1 Header
    #content
      = yield
There are a few benefits to this:
  • the information density is greater, so more of the template is visible on screen.
  • less characters to type, so less chance to make a typo
  • nesting is clearly visible, and no more issues with missing end tags.
Andrew Brown
  • Authority 512
Post Body
Andrew Brown said:

So much cleaner. 5 mins in and it felt natural Converted one of my Rails apps over to it.

  • Quote
  • Posted 4 months ago.
Andrew Brown
  • Authority 512
Post Body
Andrew Brown said:

Also probably good idea to also pick up the rspec-haml-scaffold-generator plugin

  • Quote
  • Posted 4 months ago.
Carsten
  • Authority 300
Post Body
Carsten said:

Also to note, there are a couple TextMate bundles that are quite handy when using Haml & Sass:

And remember to use Soft Tabs set to 2 spaces when editing Haml or Sass files.

  • Quote
  • Posted 4 months ago.
Andrew Brown
  • Authority 512
Post Body
Andrew Brown said:

Changing Tab Size is down below

And seeing if you have any nasty hard tabs hiding

  • Quote
  • Posted 4 months ago.
  • Your comment will be modifiable for 10 minutes after posted.

Page Author

Avatar
wmoxam
Name
wmoxam

From Here You Can…

Information

  • 1332 Views
  • 4 Comments
  • Ratings Likes 3 Negative 0

Most Recent Related Content

Published In…

This work is public domain.