Skip to content

Whitespace operators

Template::HAML supports HAML's whitespace-removal modifiers and whitespace-preservation behaviors so you can control how generated HTML is laid out.

Outer trim >

A trailing > on a tag strips whitespace immediately around the tag, both before its open tag and after its close tag.

1
2
3
%p first
%p> middle
%p last
1
<p>first</p><p>middle</p><p>last</p>

This works for any tag, including void elements:

1
2
3
%img
%img>
%img
1
<img><img><img>

Inner trim <

A trailing < on a tag strips whitespace immediately inside the tag, both after the open tag and before the close tag.

1
2
3
%blockquote<
  %div
    Foo!
1
2
3
<blockquote><div>
  Foo!
</div></blockquote>

When combined with content on the same line plus a single child, the child renders inline:

1
2
%p< hello
  %strong world
1
<p>hello<strong>world</strong></p>

Combined <> / ><

Both modifiers can be combined in either order:

1
2
%p<>
  %a hi
1
<p><a>hi</a></p>

Preserved tags

The pre and textarea elements automatically preserve their inner whitespace by replacing newlines with the &#x000A; HTML entity. This keeps the rendered display intact while still allowing HAML to indent the source.

1
2
3
%pre
  Line 1
  Line 2
1
<pre>&#x000A;  Line 1&#x000A;  Line 2&#x000A;</pre>

The list of preserved elements is configurable via the preserve option on Template::HAML::Config:

1
2
my $cfg = Template::HAML::Config.new(:preserve('pre', 'textarea', 'code'));
HAML.render(:src($haml), :config($cfg));

Global whitespace removal

To apply > and < to every tag at once, set remove-whitespace: True on the config. See Configuration for details. Preserved tags keep their inner whitespace but still have outer whitespace stripped.

Forced preserve ~

The ~ operator works like = (eval and emit), but additionally replaces newlines in the result with &#x000A;. This is useful when an interpolated string contains newlines you want to keep literal in the rendered output.

1
~ "line1\nline2"
1
line1&#x000A;line2

Like =, the result is HTML-escaped by default. Disable escaping globally with escape_html => False on the config.