Rails:将文本字段的换行符转换为<br />

Ada*_*ton 16 html ruby-on-rails line-breaks

我的模型中有一个名为"about"的文本字段,我试图在显示页面上显示,但没有任何换行符正确显示.

我尝试了很多东西,但我最终登陆的代码是:

<%= (h @template.about).gsub("\n", "<br />") %>
Run Code Online (Sandbox Code Playgroud)

不幸的是,Rails似乎正在逃避所需的HTML并输出这些换行符

Thanks for the fish, guys! Not like I wanted it, but... uh... thanks? &lt;br /&gt;
Run Code Online (Sandbox Code Playgroud)

如何将文本字段的"\n"换行符正确转换为实际的换行符HTML?我已经尝试过简单的格式,但无济于事......

我正在使用Rails 3,前几行'about'是:

谢谢你的鱼,伙计们!不像我想要的那样,但是......呃......谢谢?
"我会做出判断,"他说!
而现在,更无用的副本,所以我可以隔离阿曼达发现的奇怪的芽.
等待!我的意思是"奇怪的虫子......"

Pri*_*ain 37

尝试

<%= simple_format @template.about %>
Run Code Online (Sandbox Code Playgroud)

http://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html#method-i-simple_format

这个对我有用 :-\

1.9.3p194 :017 > str = "Thanks for the fish, guys! Not like I wanted it, but... uh... thanks? 
1.9.3p194 :018"> \"I'll be the judge of that,\" he said! 
1.9.3p194 :019"> And now, more useless copy so I can isolate that weird bud that Amanda found. 
1.9.3p194 :020"> Wait! I meant 'weird bug..."
 #=> "Thanks for the fish, guys! Not like I wanted it, but... uh... thanks? \n\"I'll be the judge of that,\" he said! \nAnd now, more useless copy so I can isolate that weird bud that Amanda found. \nWait! I meant 'weird bug..."


1.9.3p194 :021 > simple_format str
 #=> "<p>Thanks for the fish, guys! Not like I wanted it, but... uh... thanks? \n<br />\"I'll be the judge of that,\" he said! \n<br />And now, more useless copy so I can isolate that weird bud that Amanda found. \n<br />Wait! I meant 'weird bug...</p>"
Run Code Online (Sandbox Code Playgroud)

或使用 gsub

1.9.3p194 :022 > str.gsub("\n", "<br />") 
 #=> "Thanks for the fish, guys! Not like I wanted it, but... uh... thanks? <br />\"I'll be the judge of that,\" he said! <br />And now, more useless copy so I can isolate that weird bud that Amanda found. <br />Wait! I meant 'weird bug..." 
Run Code Online (Sandbox Code Playgroud)