问题描述
在我的 Rails 3.1 应用程序中,我有一个用于评论的文本字段,我希望能够允许人们包含可点击的链接(而不仅仅是显示为纯文本的 url),以及让文本字段识别何时用户在他们的文本字段中有换行符(没有用户添加 html).我该怎么做?
In my Rails 3.1 app, I have a text field for comments and I want to be able to allow people to include clickable links (instead of just the url showing as plain text), as well as having the text field recognize when a user had line breaks in their text field (without the user adding html). How can I do this?
如果用户将 html 放在 href 中,这适用于显示链接:
This works for showing a link if a user puts the html for a href:<%= simple_format(@user.description) %>
这适用于识别和显示 text_field 中回车符的换行符:<%= h(@user.description).gsub(/\n/, '<br/>').html_safe %>
And this works for recognizing and displaying the line breaks from carriage returns in the text_field:<%= h(@user.description).gsub(/\n/, '<br/>').html_safe %>
但是,我还没有想出如何同时进行.
However, I haven't figured out how to do both, together.
推荐答案
这个怎么样?
#Doesnt work in this case
#<%= simple_format( h(@user.description).gsub(/\n/, '<br/>') ).html_safe %>
似乎您需要 auto_link
功能来实现这一点.尽管它已从 rails 3.1 中移除,但它仍可作为 gem 使用.所以如果您使用的是 rails 3.1 或更高版本,您需要从单独的 gem 中获取它
Seems like you need auto_link
function to achieve this. Though it is removed from rails 3.1 it is available as a gem. So if you are using rails 3.1 or later you need to get this from a separate 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)) %>
auto_link
不仅转换网址,还转换可点击链接中的电子邮件地址.在此处获取文档.
auto_link
not only converts urls but also email addresses in clickable link. Get the document here.
参考链接:
- http://rubygems.org/gems/rails_autolink
- http://apidock.com/rails/ActionView/Helpers/TextHelper/auto_link
这篇关于在 Rails 中的文本字段中显示链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!