html - rails : Converting a text field's linebreaks into <br/>

标签 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”的前几行是:

Thanks for the fish, guys! Not like I wanted it, but... uh... thanks?
"I'll be the judge of that," he said!
And now, more useless copy so I can isolate that weird bud that Amanda found.
Wait! I meant 'weird bug...'

最佳答案

尝试

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

关于html - rails : Converting a text field's linebreaks into <br/>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12078467/

相关文章:

php - Rails、PHP 和参数

android - 在 Html.fromHtml() 之后删除多余的换行符

graphviz - 使用graphviz,HTML换行

php - 使用 SplFileObject 转换 CR 换行符

javascript - 如何组合单选和输入框中的值并在单击按钮时打开 url?

html - jquery mobile anchor 链接不起作用

ruby-on-rails - 用户 first_name last_name 字段创建一个 full_name 字段

javascript - 在保存之前使用 JQuery/Javascript 预处理在线表单

java - 如何将 html block 插入到 java servlet 中

javascript - 在 Rails 4 中使用 AJAX 进行搜索、排序和分页