在我的 Rails 3.1 应用程序中,我有一个用于评论的文本字段,我希望能够允许人们包含可点击的链接(而不仅仅是显示为纯文本的 url),以及让文本字段识别用户何时有文本字段中的换行符(无需用户添加 html)。我怎样才能做到这一点?
如果用户将 html 放在 href 中,这适用于显示链接:
<%= simple_format(@user.description) %>
这适用于识别和显示 text_field 中回车符的换行符:
<%= h(@user.description).gsub(/\n/, '<br/>').html_safe %>
但是,我还没有想出如何一起做。
这个怎么样?
#Doesnt work in this case
#<%= simple_format( h(@user.description).gsub(/\n/, '<br/>') ).html_safe %>
Run Code Online (Sandbox Code Playgroud)
编辑:
似乎你需要auto_link功能来实现这一点。尽管它已从 rails 3.1 中移除,但它仍可作为 gem 使用。因此,如果您使用的是 rails 3.1 或更高版本,则需要从单独的 gem 中获取它
#in Gemfile
gem "rails_autolink", "~> 1.0.9"
#in application.rb
require 'rails_autolink'
#Run
bundle install
#now in you view use it like
<%= h auto_link(simple_format(text)) %>
Run Code Online (Sandbox Code Playgroud)
auto_link不仅可以转换网址,还可以转换可点击链接中的电子邮件地址。在此处获取文档。
参考链接:
| 归档时间: |
|
| 查看次数: |
2351 次 |
| 最近记录: |