Displaying Only the first x words of a string in rails

前端 未结 4 826
眼角桃花
眼角桃花 2020-12-31 08:47
<%= message.content %>

I can display a message like this, but in some situations I would like to display only the first 5 words of the st

4条回答
  •  春和景丽
    2020-12-31 09:35

       # Message helper
       def content_excerpt(c)
         return unlessc
         c.split(" ")[0..4].join + "..."
       end
    
       # View
       <%= message.content_excerpt %>
    

    But the common way is truncate method

       # Message helper
       def content_excerpt(c)
         return unless c
         truncate(c, :length => 20)
       end
    

提交回复
热议问题