instance method
truncate
Ruby on Rails 6.0.6
Since v2.2.3Signature
truncate(text, options = {}, &block)
Truncates a given text after a given :length if text is longer than :length (defaults to 30). The last characters will be replaced with the :omission (defaults to “…”) for a total length not exceeding :length.
Pass a :separator to truncate text at a natural break.
Pass a block if you want to show extra content when the text is truncated.
The result is marked as HTML-safe, but it is escaped by default, unless :escape is false. Care should be taken if text contains HTML tags or entities, because truncation may produce invalid HTML (such as unbalanced or incomplete tags).
truncate("Once upon a time in a world far far away") # => "Once upon a time in a world..." truncate("Once upon a time in a world far far away", length: 17) # => "Once upon a ti..." truncate("Once upon a time in a world far far away", length: 17, separator: ' ') # => "Once upon a..." truncate("And they found that many people were sleeping better.", length: 25, omission: '... (continued)') # => "And they f... (continued)" truncate("<p>Once upon a time in a world far far away</p>") # => "<p>Once upon a time in a wo..." truncate("<p>Once upon a time in a world far far away</p>", escape: false) # => "<p>Once upon a time in a wo..." truncate("Once upon a time in a world far far away") { link_to "Continue", "#" } # => "Once upon a time in a wo...<a href="#">Continue</a>"
Parameters
-
textreq -
optionsopt = {} -
blockblock
Source
# File actionview/lib/action_view/helpers/text_helper.rb, line 94
def truncate(text, options = {}, &block)
if text
length = options.fetch(:length, 30)
content = text.truncate(length, options)
content = options[:escape] == false ? content.html_safe : ERB::Util.html_escape(content)
content << capture(&block) if block_given? && text.length > length
content
end
end
Defined in actionview/lib/action_view/helpers/text_helper.rb line 94
· View on GitHub
· Improve this page
· Find usages on GitHub
Defined in ActionView::Helpers::TextHelper