开发者

How do I stop auto_link from escaping angle brackets?

I would like for my app to allow users to post links in their posts, and for those links to automatically be recognized. To do so, I have been using auto_link as such: the following is the partial that is called to show a person's post:

_post.html.erb:

 <tr>
 开发者_运维问答    <td >
    <span class="post_header"><h4><%= link_to "#{post.user.first_name} #{post.user.last_name}", post.user %></h4></span>
    <p> <%= auto_link(post.content) %> </p>
    <span class="post_timestamp">
        Opined <%= time_ago_in_words(post.created_at) %> ago
    </span>
     </td>
 </tr>

this outputs the following, for a single post.content:

 <p> Wondering if this link &lt;a href=&quot;http://www.economist.com/blogs/freeexchange&quot;&gt;http://www.economist.com/blogs/freeexchange&lt;/a&gt; will become a proper link

Why does auto-link create/escape the angle brackets to <a etc? Is there some way to fix this, as this does not create working links. Instead the output in the browser is:

 Wondering if this link <a href="http://www.economist.com/blogs/freeexchange">http://www.economist.com/blogs/freeexchange</a> will become a proper link


In Rails 3, erb will default to not allow any ruby output to contain html. To get around this you can use "some string".html_safe

<%= auto_link(post.content).html_safe %>

But of course any html or javascript will then be allowed. So...

<%= sanitize(auto_link(post.content).html_safe) %>


Note that auto_link was removed with Rails 3.1.

See this answer for replacement solutions.


tybro0103's solution works, but if you want ONLY links as proper HTML, you'll need

sanitize(auto_link(post.content).html_safe,tags:'a')
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜