开发者

Formatting populated textarea, carriage returns, newlines, and HAML

开发者 https://www.devze.com 2023-01-04 12:18 出处:网络
When i populate a textarea with text using \\r\\n (carriage return - newline) the text is forma开发者_JS百科tted improperly [UPDATE: \\r\\n is what is generated when filling out a textarea, i\'m simpl

When i populate a textarea with text using \r\n (carriage return - newline) the text is forma开发者_JS百科tted 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.


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.


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


Continuing with @nex3's answer, if you want to do some multi-line content inside a textarea, try it like this:

%textarea#textarea_id{:name => 'area_name'}
  :preserve
    Line1
    Line2
    Line3
    Line4
    Line5


Changing

%textarea  
  = "hello\r\nHow are you?"  

to

%textarea "hello\r\nHow are you?"

all on one line seems to have solved the problem. I guess that means it was a HAML issue.

0

精彩评论

暂无评论...
验证码 换一张
取 消