16

我的模型中有一个名为“about”的文本字段,我试图在显示页面上显示它,但没有一个换行符正确显示。

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

<%= (h @template.about).gsub("\n", "<br />") %>

不幸的是,Rails 似乎正在转义所需的 HTML 并将这些换行符输出为

Thanks for the fish, guys! Not like I wanted it, but... uh... thanks? &lt;br /&gt;

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

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

谢谢你的鱼,伙计们!不是我想要的,但是……呃……谢谢?
“我会做这件事的评判者,”他说!
现在,还有更多无用的副本,这样我就可以分离出阿曼达发现的那个奇怪的芽。
等待!我的意思是“奇怪的错误……”

4

2 回答 2

37

尝试

<%= simple_format @template.about %>

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>"

或使用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..." 
于 2012-08-22T17:47:39.160 回答
3
<%= (h @template.about).gsub("\n", "<br />").html_safe %>

h助手会转义文本,这样您就不会受到 XSS 攻击。一旦该文本被转义,您就可以gsub将新字符串声明为html_safe.

html_safe不是转义,它是不应该转义字符串的声明。但是您确实想转义原始字符串,除非您确定它不包含用户输入。

于 2015-01-24T19:26:06.690 回答