Quick HAML tip: Preserve Whitespace
October 10th, 2007
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”
Sorry, comments are closed for this article.

October 18th, 2007 at 05:56 PM 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
November 6th, 2007 at 04:44 PM I second Mikel. Thanks for posting!
November 7th, 2007 at 10:22 AM No problem. I am glad I could help you out with this.
December 3rd, 2007 at 11:24 PM 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 ...
December 10th, 2007 at 10:27 AM 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?
January 7th, 2008 at 10:35 AM 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.