When i populate a textarea with text using \r\n (carriage return - newline) the text is formatted improperly [UPDATE: \r\n is what is generated when filling out a textarea, i'm simply pulling from a database what was previously filled in. Also to note, in the production environment i don't seem to have this problem. END UPDATE] For example:
%textarea
= "hello\r\nHow are you?"
comes out like this:
hello
How are you?
I'm thinking this might have something to do with HAML. Can anyone help me out? Note: if i use \n\r it works fine, but thats technically incorrect and id have to do some gsubs to reverse them for proper display.
Short answer if = f.text_area :foo
displays unwanted white-space at each newline:
replace =
with ~
For a more detailed explanation for the reasons behind it, read Natalie's answer and the HAML docs about ~.
Because Haml automatically indents the HTML source code, the contents of whitespace-sensitive tags like pre and textarea can get screwed up. The solution is to replace the newlines inside these tags with HTML newline entities 

, which Haml does using the Haml::Helpers#preserve
and Haml::Helpers#find_and_preserve
helpers.
Normally, Haml will do this for you automatically when you’re using a tag that needs it (this can be customized using the :preserve
option). For example,
%p
%textarea= "Foo\nBar"
will be compiled to
<p>
<textarea>
Foo
Bar</textarea>
</p>
However, if a helper is generating the tag, Haml can’t detect that and so you’ll have to call Haml::Helpers#find_and_preserve
yourself. You can also use ~
, which is the same as =
except that it automatically runs find_and_preserve
on its input. For example:
%p= find_and_preserve "<textarea>Foo\nBar</textarea>"
is the same as
%p~ "<textarea>Foo\nBar</textarea>"
and renders
<p><textarea>Foo
Bar</textarea></p>
Source: this Haml FAQ.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With