Haml (HTML Abstraction Markup Language)

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, ERB, and ASP.
However, Haml avoids the need for explicitly coding HTML into the template,
because it is actually an abstract description of the HTML, with some code to
generate dynamic content.

Features

Whitespace active

Well-formatted markup

DRY

Follows CSS conventions

Integrates Ruby code

Implements Rails templates with the .haml extension

Using Haml

Haml can be used in three ways:

as a command-line tool,

as a plugin for Ruby on Rails,

and as a standalone Ruby module.

The first step for all of these is to install the Haml gem:

gem install haml

To run Haml from the command line, just use

haml input.haml output.html

Use haml --help for full documentation.

To use Haml with Rails, add the following line to the Gemfile:

gem "haml"

Once it's installed, all view files with the ".html.haml" extension will be
compiled using Haml.

You can access instance variables in Haml templates the same way you do in ERB
templates. Helper methods are also available in Haml templates. For example:

Rails XSS Protection

Haml supports Rails' XSS protection scheme, which was introduced in Rails 2.3.5+
and is enabled by default in 3.0.0+. If it's enabled, Haml's
{Haml::Options#escape_html :escape_html} option is set to true by default -
like in ERB, all strings printed to a Haml template are escaped by default. Also
like ERB, strings marked as HTML safe are not escaped. Haml also has its own
syntax for printing a raw string to the template.

If the :escape_html option is set to false when XSS protection is enabled,
Haml doesn't escape Ruby strings by default. However, if a string marked
HTML-safe is passed to Haml's escaping syntax, it won't be
escaped.

Finally, all the {Haml::Helpers Haml helpers} that return strings that are known
to be HTML safe are marked as such. In addition, string input is escaped unless
it's HTML safe.

Ruby Module

Haml can also be used completely separately from Rails and ActionView. To do
this, install the gem with RubyGems:

gem install haml

You can then use it by including the "haml" gem in Ruby code, and using
{Haml::Engine} like so:

Outside Rails, you can set them by configuring them globally in
Haml::Options.defaults:

Haml::Options.defaults[:format] = :html5

Finally, you can also set them by passing an options hash to
{Haml::Engine#initialize}. For the complete list of available options, please
see {Haml::Options}.

Encodings

When using Ruby 1.9 or later, Haml supports the same sorts of
encoding-declaration comments that Ruby does. Although both Ruby and Haml
support several different styles, the easiest it just to add -# coding:
encoding-name at the beginning of the Haml template (it must come before all
other lines). This will tell Haml that the template is encoded using the named
encoding.

By default, the HTML generated by Haml has the same encoding as the Haml
template. However, if Encoding.default_internal is set, Haml will attempt to
use that instead. In addition, the :encoding option can be
used to specify an output encoding manually.

Note that, like Ruby, Haml does not support templates encoded in UTF-16 or
UTF-32, since these encodings are not compatible with ASCII. It is possible to
use these as the output encoding, though.

Plain Text

A substantial portion of any HTML document is its content, which is plain old
text. Any Haml line that's not interpreted as something else is taken to be
plain text, and passed through unmodified. For example:

%gee
%whiz
Wow this is cool!

is compiled to:

<gee>
<whiz>
Wow this is cool!
</whiz>
</gee>

Note that HTML tags are passed through unmodified as well. If you have some HTML
you don't want to convert to Haml, or you're converting a file line-by-line, you
can just include it as-is. For example:

%p
<div id="blah">Blah!</div>

is compiled to:

<p>
<div id="blah">Blah!</div>
</p>

Escaping: \

The backslash character escapes the first character of a line, allowing use of
otherwise interpreted characters as plain text. For example:

%title
= @title
\= @title

is compiled to:

<title>
MyPage
= @title
</title>

HTML Elements

Element Name: %

The percent character is placed at the beginning of a line. It's followed
immediately by the name of an element, then optionally by modifiers (see below),
a space, and text to be rendered inside the element. It creates an element in
the form of <element></element>. For example:

%one
%two
%three Hey there

is compiled to:

<one>
<two>
<three>Hey there</three>
</two>
</one>

Any string is a valid element name; Haml will automatically generate opening and
closing tags for any element.

Attributes: {} or () {#attributes}

Brackets represent a Ruby hash that is used for specifying the attributes of an
element. It is literally evaluated as a Ruby hash, so logic will work in it and
local variables may be used. Quote characters within the attribute will be
replaced by appropriate escape sequences. The hash is placed after the tag is
defined. For example:

You can use as many such attribute methods as you want by separating them with
commas, like a Ruby argument list. All the hashes will me merged together, from
left to right. For example, if you defined

Note that the Haml attributes list has the same syntax as a Ruby method call.
This means that any attribute methods must come before the hash literal.

Attribute methods aren't supported for HTML-style attributes.

Boolean Attributes

Some attributes, such as "checked" for input tags or "selected" for option
tags, are "boolean" in the sense that their values don't matter - it only
matters whether or not they're present. In HTML (but not XHTML), these
attributes can be written as

<input selected>

To do this in Haml using hash-style attributes, just assign a Ruby true value
to the attribute:

%input{:selected => true}

In XHTML, the only valid value for these attributes is the name of the
attribute. Thus this will render in XHTML as

<input selected='selected'>

To set these attributes to false, simply assign them to a Ruby false value. In
both XHTML and HTML,

%input{:selected => false}

will just render as:

<input>

HTML-style boolean attributes can be written just like HTML:

%input(selected)

or using true and false:

%input(selected=true)

HTML5 Custom Data Attributes

HTML5 allows for adding custom non-visible data
attributes
to elements using attribute names beginning with data-. Custom data attributes
can be used in Haml by using the key :data with a Hash value in an attribute
hash. Each of the key/value pairs in the Hash will be transformed into a custom
data attribute. For example:

%a{:href=>"/posts", :data => {:author_id => 123}} Posts By Author

will render as:

<a data-author-id='123' href='/posts'>Posts By Author</a>

Notice that the underscore in author_id was replaced by a hyphen. If you wish
to suppress this behavior, you can set Haml's :hyphenate_data_attrs
option to false, and the output will be
rendered as:

<a data-author_id='123' href='/posts'>Posts By Author</a>

Class and ID: . and #

The period and pound sign are borrowed from CSS. They are used as shortcuts to
specify the class and id attributes of an element, respectively. Multiple
class names can be specified in a similar way to CSS, by chaining the class
names together with periods. They are placed immediately after the tag and
before an attributes hash. For example:

Self-Closing Tags: /

The forward slash character, when placed at the end of a tag definition, causes
the tag to be self-closed. For example:

%br/
%meta{'http-equiv' => 'Content-Type', :content => 'text/html'}/

is compiled to:

<br />
<meta http-equiv='Content-Type' content='text/html' />

Some tags are automatically closed, as long as they have no content. meta,
img, link, script, br, and hr tags are closed by default. This list
can be customized by setting the :autoclose option. For
example:

%br
%meta{'http-equiv' => 'Content-Type', :content => 'text/html'}

is also compiled to:

<br />
<meta http-equiv='Content-Type' content='text/html' />

Whitespace Removal: > and <

> and < give you more control over the whitespace near a tag. > will
remove all whitespace surrounding a tag, while < will remove all whitespace
immediately within a tag. You can think of them as alligators eating the
whitespace: > faces out of the tag and eats the whitespace on the outside, and
< faces into the tag and eats the whitespace on the inside. They're placed at
the end of a tag definition, after class, id, and attribute declarations but
before / or =. For example:

%blockquote<
%div
Foo!

is compiled to:

<blockquote><div>
Foo!
</div></blockquote>

And:

%img
%img>
%img

is compiled to:

<img /><img /><img />

And:

%p<= "Foo\nBar"

is compiled to:

<p>Foo
Bar</p>

And finally:

%img
%pre><
foo
bar
%img

is compiled to:

<img /><pre>foo
bar</pre><img />

Object Reference: []

Square brackets follow a tag definition and contain a Ruby object that is used
to set the class and id of that tag. The class is set to the object's class
(transformed to use underlines rather than camel case) and the id is set to the
object's class, followed by the value of its #to_key or #id method (in that
order). This is most useful for elements that represent instances of Active
Model models. Additionally, the second argument (if present) will be used as a
prefix for both the id and class attributes. For example:

Running Ruby: -

The hyphen character is also followed by Ruby code. This code is evaluated but
not inserted into the document.

It is not recommended that you use this widely; almost all processing code and
logic should be restricted to Controllers, Helpers, or partials.

For example:

- foo = "hello"
- foo << " there"
- foo << " you!"
%p= foo

is compiled to:

<p>
hello there you!
</p>

A line of Ruby code can be stretched over multiple lines as long as each line
but the last ends with a comma. For example:

- links = {:home => "/",
:docs => "/docs",
:about => "/about"}

Ruby Blocks

Ruby blocks, like XHTML tags, don't need to be explicitly closed in Haml.
Rather, they're automatically closed, based on indentation. A block begins
whenever the indentation is increased after a Ruby evaluation command. It ends
when the indentation decreases (as long as it's not an else clause or
something similar). For example:

Escaping HTML: &= {#escaping_html}

An ampersand followed by one or two equals characters evaluates Ruby code just
like the equals without the ampersand, but sanitizes any HTML-sensitive
characters in the result of the code. For example:

&= "I like cheese & crackers"

compiles to

I like cheese &amp; crackers

If the {Haml::Options#escape_html :escape_html} option is set, &= behaves
identically to =.

& can also be used on its own so that #{} interpolation is escaped. For
example,

& I like #{"cheese & crackers"}

compiles to:

I like cheese &amp; crackers

Unescaping HTML: != {#unescaping_html}

An exclamation mark followed by one or two equals characters evaluates Ruby code
just like the equals would, but never sanitizes the HTML.

By default, the single equals doesn't sanitize HTML either. However, if the
{Haml::Options#escape_html :escape_html} option is set, = will sanitize the
HTML, but != still won't. For example, if :escape_html is set:

= "I feel <strong>!"
!= "I feel <strong>!"

compiles to

I feel &lt;strong&gt;!
I feel <strong>!

! can also be used on its own so that #{} interpolation is unescaped.
For example,

! I feel #{"<strong>"}!

compiles to

I feel <strong>!

Filters {#filters}

The colon character designates a filter. This allows you to pass an indented
block of text as input to another filtering program and add the result to the
output of Haml. The syntax is simply a colon followed by the name of the filter.
For example:

Currently, filters ignore the {Haml::Options#escape_html :escape_html} option.
This means that #{} interpolation within filters is never HTML-escaped.

The functionality of some filters such as Markdown can be provided by many
different libraries. Usually you don't have to worry about this - you can just
load the gem of your choice and Haml will automatically use it.

However in some cases you may want to make Haml explicitly use a specific gem to
be used by a filter. In these cases you can do this via Tilt, the library Haml
uses to implement many of its filters:

:cdata

:coffee

Compiles the filtered text to Javascript using Cofeescript. You can also
reference this filter as :coffeescript. This filter is implemented using
Tilt.

{#css-filter}

:css

Surrounds the filtered text with <style> and (optionally) CDATA tags. Useful
for including inline CSS. Use the {Haml::Options#cdata :cdata option} to
control when CDATA tags are added.

{#erb-filter}

:erb

Parses the filtered text with ERb, like an RHTML template. Not available if the
:suppress_eval option is set to true. Embedded Ruby
code is evaluated in the same context as the Haml template. This filter is
implemented using Tilt.

{#escaped-filter}

:escaped

Works the same as plain, but HTML-escapes the text
before placing it in the document.

{#javascript-filter}

:javascript

Surrounds the filtered text with <script> and (optionally) CDATA tags.
Useful for including inline Javascript. Use the {Haml::Options#cdata :cdata
option} to control when CDATA tags are added.

{#less-filter}

:less

Parses the filtered text with Less to produce CSS output.
This filter is implemented using Tilt.

{#markdown-filter}

:markdown

Parses the filtered text with
Markdown. This filter is
implemented using Tilt.

{#maruku-filter}

:maruku

Parses the filtered text with Maruku, which
has some non-standard extensions to Markdown.

As of Haml 3.2, this filter is defined in Haml
contrib but is loaded automatically for
historical reasons. In future versions of Haml it will likely not be loaded by
default. This filter is implemented using Tilt.

{#plain-filter}

:plain

Does not parse the filtered text. This is useful for large blocks of text
without HTML tags, when you don't want lines starting with . or - to be
parsed.

{#preserve-filter}

:preserve

Inserts the filtered text into the template with whitespace preserved.
preserved blocks of text aren't indented, and newlines are replaced with the
HTML escape code for newlines, to preserve nice-looking output. See also
Whitespace Preservation.

{#ruby-filter}

:ruby

Parses the filtered text with the normal Ruby interpreter. All output sent to
$stdout, like with puts, is output into the Haml document. Not available if
the :suppress_eval option is set to true. The Ruby
code is evaluated in the same context as the Haml template.

{#sass-filter}

:sass

Parses the filtered text with Sass to produce CSS
output. This filter is implemented using Tilt.

{#scss-filter}

:scss

Parses the filtered text with Sass like the :sass filter, but uses the newer
SCSS syntax to produce CSS output. This filter is implemented using Tilt.

{#textile-filter}

:textile

Parses the filtered text with Textile.
Only works if RedCloth is installed.

As of Haml 3.2, this filter is defined in Haml
contrib but is loaded automatically for
historical reasons. In future versions of Haml it will likely not be loaded by
default. This filter is implemented using Tilt.

Custom Filters

You can also define your own filters. See {Haml::Filters} for details.

Multiline: | {#multiline}

The pipe character designates a multiline string.
It's placed at the end of a line (after some whitespace)
and means that all following lines that end with |
will be evaluated as though they were on the same line.
Note that even the last line in the multiline block
should end with |.
For example:

%whoo
%hoo= h( |
"I think this might get " + |
"pretty long so I should " + |
"probably make it " + |
"multiline so it doesn't " + |
"look awful.") |
%p This is short.

is compiled to:

<whoo>
<hoo>I think this might get pretty long so I should probably make it multiline so it doesn't look awful.</hoo>
<p>This is short</p>
</whoo>

Using multiline declarations in Haml is intentionally awkward.
This is designed to discourage people from putting lots and lots of Ruby code
in their Haml templates.
If you find yourself using multiline declarations, stop and think:
could I do this better with a helper?

Note that there are a few cases where it's useful to allow
something to flow over onto multiple lines in a non-awkward manner.
One of these is HTML attributes.
Some elements just have lots of attributes,
so you can wrap attributes without using | (see Attributes).

In addition, sometimes you need to call Ruby methods or declare data structures
that just need a lot of template information.
So data structures and functions that require lots of arguments
can be wrapped over multiple lines,
as long as each line but the last ends in a comma
(see Inserting Ruby).

Whitespace Preservation

Sometimes you don't want Haml to indent all your text.
For example, tags like pre and textarea are whitespace-sensitive;
indenting the text makes them render wrong.

Haml deals with this by "preserving" newlines before they're put into the document --
converting them to the HTML whitespace escape code, &#x000A;.
Then Haml won't try to re-format the indentation.

Literal textarea and pre tags automatically preserve content given through =.
Dynamically-generated textareas and pres can't be preserved automatically,
and so should be passed through {Haml::Helpers#find_and_preserve} or the ~ command,
which has the same effect.

Helpers

Haml offers a bunch of helpers that are useful for doing stuff like preserving
whitespace, creating nicely indented output for user-defined helpers, and other
useful things. The helpers are all documented in the {Haml::Helpers} and
{Haml::Helpers::ActionViewExtensions} modules.