Limiting characters/words in view - ruby on rails

前端 未结 4 2001
情深已故
情深已故 2021-02-03 20:43

I am displaying recent comments on the home page of a very simple blog application I am building in Ruby on Rails. I want to limit the number of characters that are displayed fr

相关标签:
4条回答
  • 2021-02-03 21:30

    I just found another way (if you don't want to add the "...")

    <%= comment.body.first(80) %>
    

    As said in the RoR API for String:

    first(limit = 1)

    Returns the first character. If a limit is supplied, returns a substring from the beginning of the string until it reaches the limit value. If the given limit is greater than or equal to the string length, returns self.

    comment = "1234567890"
    
    comment.first(5)
    # => "12345"
    
    comment.first(10)
    # => "1234567890"
    
    comment.first(15)
    # => "1234567890"
    
    0 讨论(0)
  • 2021-02-03 21:34

    If you are using rails 4.2 or above then you can use truncate_words method.

    For example:
    "In a world where everything is awesome".truncate_words(3)

    Output: "In a world..."

    0 讨论(0)
  • 2021-02-03 21:40

    Try the truncate view helper

    <%=h truncate(comment.body, :length => 80) %>
    
    0 讨论(0)
  • 2021-02-03 21:40

    You can also use the truncate method if you want to limit the number of characters. I'm using this to display just enough characters in a bootstrap row to somewhat match the height of an image displayed in the same row.

    <%= "#{message.truncate(charcount)}" %>
    
    0 讨论(0)
提交回复
热议问题