All*_*Cat 5 html string truncate ruby-on-rails
我目前正在尝试截断任何超过65个字符的字符串.
我的代码是
<title><%= truncate(title.html_safe, length:65) %></title>
Run Code Online (Sandbox Code Playgroud)
它适用于超过65个字符的标题.但是正好65个字符的标题仍然会被截断.
例如:
标题:"这篇文章正好是65个字符的字符字符"
在页面上显示"此帖子正好是65个字符的字符字符..."
我不应该使用truncate吗?
truncate是正确的方法.这可能是您的rails版本中的错误?这是我在控制台上得到的内容:
[5] pry(main)> helper.truncate("This post is exactly 56 characters characters characters characte", length: 65)
=> "This post is exactly 56 characters characters characters characte"
[6] pry(main)> helper.truncate("This post is exactly 56 characters characters characters characte", length: 64)
=> "This post is exactly 56 characters characters characters char..."
Run Code Online (Sandbox Code Playgroud)
我在这个例子中运行Rails 4.0.4.
如果您正在使用
rails 4.2或以上,那么您可以使用truncate_words方法。
<title><%= (title.html_safe).truncate_words(5) %></title>
Run Code Online (Sandbox Code Playgroud)