Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting populated textarea, carriage returns, newlines, and HAML

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.

like image 422
Michael Avatar asked Jun 18 '10 17:06

Michael


2 Answers

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 ~.

like image 62
thutt Avatar answered Oct 13 '22 03:10

thutt


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.

like image 35
Natalie Weizenbaum Avatar answered Oct 13 '22 04:10

Natalie Weizenbaum