开发者

How can I limit the amount of words displayed from a Ruby string?

开发者 https://www.devze.com 2023-01-11 03:28 出处:网络
the Ruby code is below: <%= product.advert_text -开发者_运维技巧%> What script can limit the amount of words?Since you are working with Rails, you can use the truncate method.

the Ruby code is below:

<%= product.advert_text -开发者_运维技巧%>

What script can limit the amount of words?


Since you are working with Rails, you can use the truncate method.

So, something like:

<%= truncate(product.advert_text, :length => 20) -%>

The :length option sets the # of characters to truncate at & will add ellipses at the end (you can override the default ellipses with the :omission option - see the documentation on my link).


If you want to limit to a certain number of words, the easiest way is going to be to split on space and then join the desired number of words back into a string.

<%=product.advert_text.split.slice(0, limit).join(" ") -%>
0

精彩评论

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