Rails 截断助手,其中链接为省略文本
我的描述很长,我想使用截断助手来截断。 所以我正在使用:
truncate article.description, :length => 200, :omission => ' ...'
问题是我想使用 more 作为可点击的链接,所以理论上我可以使用这个:
truncate article.description, :length => 200, :omission => "... #{link_to('[more]', articles_path(article)}"
省略文本被视为不安全,因此被转义。我试图将其设置为 html_safe 但它不起作用,而不是链接 [更多] 我的浏览器仍然显示该链接的 html。
有没有办法强制截断打印省略链接而不是省略文本?
I'm quite long description that I want to truncate using truncate helper.
So i'm using the:
truncate article.description, :length => 200, :omission => ' ...'
The problem is that I want to use more as a clickable link so in theory I could use this:
truncate article.description, :length => 200, :omission => "... #{link_to('[more]', articles_path(article)}"
Omission text is handled as unsafe so it's escaped. I tried to make it html_safe but it didn't work, instead of link [more] my browser is still showing the html for that link.
Is there any way to force truncate to print omission link instead of omission text?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
使用 Rails 4,您可以/应该传递链接块:
With Rails 4, you can/should pass in a block for the link:
我建议您在辅助方法中自行执行此操作,这样您也可以对输出有更多的控制:
I would suggest doing this on your own in a helper method, that way you'll have a little more control over the output as well:
肮脏的解决方案...使用“原始”方法来取消转义它。
您必须确保内容的“合理性”。
raw 是一个类似于 html_safe 的助手。
bye
edit: 不是转义的遗漏,而是truncate方法的结果。
Dirty solution... use the method "raw" to unescape it.
you have to be sure of "sanity" of your content.
raw is a helper acting like html_safe .
bye
edit: is not the omission of being escaped , but the result of truncate method.
我遇到了类似的情况,这解决了问题。尝试(为了可读性而换行):
您可以使用 h 来确保文章描述的完整性,并且由于您将 link_to 设置为您知道不是潜在恶意的路径,因此您可以将结果字符串标记为 html_safe ,无需担心。
I encountered a similar situation and this did the trick. Try (line breaks for readability):
You can use h to ensure sanity of article description, and since you are setting the link_to to a path you know to not be something potentially nefarious, you can mark the resulting string as html_safe without concern.
TextHelper#truncate
有一个 块truncate
的形式,它允许您使用未转义的link_to
,同时仍转义截断的文本:TextHelper#truncate
has a block form oftruncate
, which lets you use alink_to
that isn't escaped, while still escaping the truncated text:唯一对我有用的:
The only one that worked for me :
我遇到了同样的问题,就我而言,我只是使用
:escape =>;假
。有效:
truncatearticle.description, :length => 200、:省略=> "... #{link_to('[more]',articles_path(article)}", :escape => false
来自文档:
I had the same problem, in my case i just used
:escape => false
.That worked:
truncate article.description, :length => 200, :omission => "... #{link_to('[more]', articles_path(article)}", :escape => false
From documentation :