Skip to content

Haml: stray whitespace in textarea

I agree with Obie and others who recommend Haml. That said, I ran into a strange issue lately: I was finding lots of extra leading spaces in a textarea.

The culprit was Haml, or, rather, my misunderstanding of it.  Haml is great for making your HTML source properly indented.  However, this means that Haml may add whitespace where you don’t want it — i.e. inside a textarea tag.  As Nathan W. says, “Haml isn’t good at not generating whitespace.”  Here is what my (flawed) Haml template looked like:

%label{:for => “goal_description”} Description:
= form.text_area :description, :rows => 8, :cols => 60

The solution is easy, use the find_and_preserve helper:

%label{:for => “goal_description”} Description:
= find_and_preserve do
  = form.text_area :description, :rows => 8, :cols => 60

3 Comments

  1. As a side note, Haml 2.0 (to be released soon) will monkeypatch the Rails text_area generators to automatically preserve their contents.

    Friday, May 16, 2008 at 5:59 pm | Permalink
  2. Tony wrote:

    Thank you so much for documenting this one. I had been analysing my CSS for quite a time, and eventually pinned it to Haml, but hadnt got a clue how to fix. So easy when you know.

    Tuesday, June 24, 2008 at 3:44 pm | Permalink
  3. Paul wrote:

    The current way to handle this is to use “~” instead of “=”. It would look like this:

    %label{:for => “goal_description”} Description:
    ~ form.text_area :description, :rows => 8, :cols => 60

    Monday, February 22, 2010 at 12:02 am | Permalink

Post a Comment

Your email is never published nor shared. Required fields are marked *
*
*