Haml Whitespace Preservation (or: Fixing Textarea Indentation in Haml)

Posted . Visible to the public.

Haml renders HTML with indentation reflecting the nesting level of elements. When it comes to white-space preserving content, this may become a problem: the content will be rendered including the HTML indentation.

Problematic: Preserved Indentation

.nest
  %span Reference
  %pre
    = content
<div class="nest">
    <span>Reference</span>
    <pre>
        Hello
        World
    </pre>
</div>

Image

Better: Without Extra Indentation

Render with tilde ~ instead of equals = to keep Haml from indenting content:

.nest
  %span Reference
  %pre
    ~ content
<div class="nest">
    <span>Reference</span>
    <pre>
Hello
World
    </pre>
</div>

Image

Textareas

In some versions of Haml + Rails, this may also be an issue for textarea elements. Fix it similarly:

# Indented description
= form.text_area :description

# Unindented description
~ form.text_area :description
Profile picture of Dominik Schöler
Dominik Schöler
Last edit
Dominik Schöler
License
Source code in this card is licensed under the MIT License.
Posted by Dominik Schöler to makandra dev (2025-03-11 09:21)