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

时间:2012-08-22 17:34:42

标签: html ruby-on-rails line-breaks

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

  

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

2 个答案:

答案 0 :(得分:34)

尝试

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

答案 1 :(得分:3)

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

h帮助转义文本,因此您不会对XSS攻击持开放态度。转义该文本后,您可以gsub并将新字符串声明为html_safe

html_safe 没有转义,这是声明字符串不应转义的声明。但是你确实希望转义原始字符串,除非你确定它不包含用户输入。