yet.org

haml

Haml (HTML abstraction markup language) is based on one primary principle: markup should be beautiful. It’s not just beauty for beauty’s sake either; Haml accelerates and simplifies template creation down to veritable haiku. Here is how Haml markup is presented on the inventor site, in this article we’ll give you the basis to start using it instead of Erb for your next web project.

Installation

% gem install haml

Usage

To create plugin hook in Rails

% haml --rails /path/to/app

To run from the command line

% haml input.haml output.html
% haml --help

Cheatsheet

Think of Haml as Erb with open/close tags replaced by strict 2-space indentation convention.

Here is the Haml Syntax Cheatsheet.

tag sample meaning
!!! !!! 5 doctype specifier like XHTML5
% %h1 element identifier
= %h1= @content.title Ruby expression
sanitize any HTML-sensitive chars if :escape_html set (default)
# #main (equivalent to %div#main) id specifier
. .content Hello, World! class specifier
{} %strong{class: code, id: message} Hello World attributes
[] %div[@content] id and class taken from Ruby object
/ (at end) %br/ self-closing tags
/ (at start) / this is a comment comments, can also wrap indented sections of code.
\ \. escape character
| multi-line string
> trim whitespace outside tag
< trim whitespace inside tags
: :markdow filter following content
- Ruby non-printing code
~ %pre~ @content.body Ruby expression preserving whitespace
== %h1== Now editing #{@content.title} Ruby interpolated string
&= %h1&= @content.title_from_user Ruby sanitized expression
!= #body!= @content.generated_html Ruby unsanitized expression
-= -# this comment will disapear Silent comment

Haml Sample

#content
 .title
   %h1= @title
   = link_to 'Home', home_url

which may compiled to

<div id='content'>
  <div class='title'>
    <h1>Teen Wolf</h1>
    <a href='/'>Home</a>
  </div>
</div>

or

%div#Article.article.entry{id: @article.number, class: @article.visibility}

which may be compiled to

<div class="article entry visible" id="Article_27">Gabba Hey</div>

Auto Convert all ERb rails views to Haml

Just drop this in your rails root folder and run it.

class ToHaml
  def initialize(path)
    @path = path
  end

  def convert!
    Dir["#{@path}/**/*.erb"].each do |file|
      `html2haml --erb --xhtml #{file} #{file.gsub(/\.erb$/, '.haml')}`
    end
  end
end

path = File.join(File.dirname(__FILE__), 'app', 'views')
ToHaml.new(path).convert!

Note: html2haml is included with Haml installation