Formatting populated textarea, carriage returns, newlines, and HAML

Michael picture Michael · Jun 18, 2010 · Viewed 8.6k times · Source

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.

Answer

Natalie Weizenbaum picture Natalie Weizenbaum · Jun 19, 2010

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&#x000A;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&#x000A;Bar</textarea></p>

Source: this Haml FAQ.