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

17

我在我的模型中有一个名为“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'的前几行内容是:

  

谢谢你们的鱼!虽然我不需要,但...嗯...还是谢谢?
  “我会判断的,”他说!
现在,更多无用的拷贝,这样我就可以隔离阿曼达发现的那个奇怪的芽。
  等等!我是说 '奇怪的 bug ...'


你在使用哪个Rails版本?同时提供@template.about的值。 - Pritesh Jain
修改了我的上面的评论以反映您的要求... - Adam Templeton
2个回答

38

尝试

<%= 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..." 

是的,这是我尝试的第一件事之一。为了确保,我再试了一次,但它并没有起作用。 - Adam Templeton
很奇怪,根据我的服务器日志,这个可以工作。我更新了文本,它变成了:<p>谢谢你们的鱼!虽然我不是很想要,但是...嗯...谢谢? <br />“我会判断的,”他说!现在,更多无用的复制,所以我可以隔离阿曼达发现的那个奇怪的 bug。 <br />等等!我是说“奇怪的 bug”...</p> 然而,在我的展示页面上,它仍然是一个巨大的文本墙... - Adam Templeton
它的显示标签是像文本中的<p>还是呈现为HTML? - Pritesh Jain
它只是不显示标签,无论是作为文本还是HTML。 - Adam Templeton
好的,那就是一个开始。有什么想法可能会搞砸它吗?或者我该如何开始寻找问题? - Adam Templeton
显示剩余4条评论

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

h助手会转义文本,以避免XSS攻击。一旦该文本被转义,您可以使用gsub并声明新字符串为html_safe

html_safe并不是进行转义,而是声明该字符串不应该被转义。但是在您确信原始字符串不包含用户输入时,需要转义原始字符串。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接