如何阻止 auto_link 转义尖括号?
我希望我的应用程序允许用户在他们的帖子中发布链接,并自动识别这些链接。为此,我一直在使用 auto_link :以下是被调用以显示个人帖子的部分内容:
_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>
对于单个 post.content 输出以下内容:
<p> Wondering if this link <a href="http://www.economist.com/blogs/freeexchange">http://www.economist.com/blogs/freeexchange</a> will become a proper link
为什么自动链接会创建/转义尖括号到
Wondering if this link <a href="http://www.economist.com/blogs/freeexchange">http://www.economist.com/blogs/freeexchange</a> will become a proper link
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 <a href="http://www.economist.com/blogs/freeexchange">http://www.economist.com/blogs/freeexchange</a> 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在 Rails 3 中,erb 默认不允许任何 ruby 输出包含 html。要解决这个问题,您可以使用
"some string".html_safe
但当然,任何 html 或 javascript 都将被允许。所以...
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
But of course any html or javascript will then be allowed. So...
请注意,Rails 3.1 中删除了 auto_link。
有关替代解决方案,请参阅此答案 。
Note that auto_link was removed with Rails 3.1.
See this answer for replacement solutions.
tybro0103 的解决方案有效,但如果您只想将链接作为正确的 HTML,则需要
tybro0103's solution works, but if you want ONLY links as proper HTML, you'll need