我使用truncate方法截断我网站中的字符串。我用代码截断:
truncate(auto_link(textilize(post.content)), :length => 140)
此截断会截断帖子内容,但内容包含链接存在问题。 EG的帖子内容是:
<p>Yahoo Yahoo Yahoo Yahoo Yahoo Yahoo Yahoo Yahoo Yahoo Yahoo Yahoo Yahoo Yahoo Yahoo
<a href="http://www.yahoo.com">Yahoo Yahoo Yahoo Yahoo Yahoo Yahoo Yahoo Yahoo Yahoo
Yahoo </a> Google Google Google Google Google Google Google Google Google Google <a
href="http://www.google.com"> Google Google Google Google Google Google Google Google
</a><br></p>
在这种情况下,所有html标签和链接都通过truncate方法计入字符数,而不是用于计算查看者实际看到的字符的truncate方法:
Yahoo Yahoo Yahoo Yahoo Yahoo Yahoo Yahoo Yahoo Yahoo Yahoo Yahoo Yahoo Yahoo Yahoo
Yahoo Yahoo Yahoo Yahoo Yahoo Yahoo Yahoo Yahoo Yahoo Yahoo (etc..)
这里有截断方法的工作吗?
编辑:清除模棱两可的新例子:
用户以纯文字发布帖子,并允许使用纺织品进行一些格式化。在发布链接方面,我允许用户(a)粘贴普通网址(http://www.site.com,www.site.com等),(b)使用纺织语法转换“点击我文字“:http://www.example.com到the click me text或花时间以html格式嵌入链接。
我想要一个页面,其中包含一个人帖子的片段,仅显示其帖子中的第一个,例如140个字符。但我希望这是一个读者会看到的140个字符的文本。换句话说,假设用户的帖子开头为:
Today I went to the market to pick up some fruit. "At the market there was this awesome
fruit display!":http://www.externalsite.com/picture.jpg Definitely want to go back
tomorrow!
这将由textilize转换为193个字符的字符串:
Today I went to the market to pick up some fruit. <a href="http://www.externalsite.com/picture.jpg">
At the market there was this awesome fruit display!</a> Definitely want to go back
tomorrow!
用户在页面上看到的文字只有138个字符:
Today I went to the market to pick up some fruit. At the market there was this awesome
fruit display! Definitely want to go back tomorrow!
193个字符长的文本会被truncate截断,但是如果我有一个解决方法,整个文本会显示出来,最后只显示138个字符并嵌入链接。
答案 0 :(得分:0)
您将返回包含其中所有链接的字符串。截断是正确的。你需要的是通过一种方法来传递事物,这种方法只会返回链接的文本(我猜这应该被截断)。
您可以使用RegEx来获取链接的字符串,例如(未经测试)
post.content.gsub /<a[\w\"]*>([a-z]*)<\/a>/i do |link_text|
truncate(auto_link(link_text), :truncate => 40)
end
答案 1 :(得分:0)
截断包含HTML代码的文本不是一个好主意。
我建议你使用纯文本。否则,替代方案将是
auto_link
这是一种黑客行为,但应该有效。同样,我建议你在截断时使用纯文本。
答案 2 :(得分:0)
对于那些感兴趣的人,要获得没有链接的准确计数,可以这样做:
count = strip_tags(string).count
(这是一个包含html标签的字符串。如果字符串需要先'textilized'等等,那么代码就是count = strip_tags(textilize(string))。count。。
不是使用truncate,而是将计数限制为此真实计数的140个字符,即将其切换为字段上的验证。