So I love HAML, and was building a form with it. I added a text_area like normal and expected everything to be fine. Well, when editing an object everything was indented. And if I saved that, it would then be indented two times. This is caused because of the indentation that HAML adds, and there is a very simple fix.

Instead of:

=f.text_area :description

Do this:

~f.text_area :description

The ~ acts like = except that it preserves the whitespace. This is also very useful with <pre>.

6 Responses to “Quick HAML tip: Preserve Whitespace”

  1. Mikel Says:
    You rock, thank you for this tip... was pulling my hair out having some haml and some rhtml and some :preserve and some :ruby filters.... I knew there must be an easier way and you came up as #1 on google... Should have looked earlier :) Thanks! Mikel
  2. Erik Says:
    I second Mikel. Thanks for posting!
  3. Ray Morgan Says:
    No problem. I am glad I could help you out with this.
  4. Yun Gao Says:
    This is a cool haml tip. I found that each time I save the text_area, indent got one more level. A quick search lead me to this link and my problem was solved! Is there an rhtml solution for this? My original code was in rhtml (scaffold generated), I had to change to haml to fix this ...
  5. Ray Morgan Says:
    Yun Gao: I wouldn't think rhtml would have a problem like this. It is caused by HAML auto indenting things to create a pretty output. Are you using a rhtml partial inside of a HAML template?
  6. Coderifous Says:
    Yun Gao: If you are in a scenario where you can't use the ~ HAML syntax, then you can apply the +preserve+ method directly. +preserve+ is provided by the HAML plugin, and is precisely what ~ uses. Example: text_area_tag("field_name", preserve(field_value)) It worked well for me.

Sorry, comments are closed for this article.