instance method truncate

Ruby on Rails 7.0.10

Since v2.2.3

Available in: v2.2.3 v2.3.18 v3.0.20 v3.1.12 v3.2.22.5 v4.0.13 v4.1.16 v4.2.9 v5.2.8.1 v6.0.6 v6.1.7.10 v7.0.10 v7.1.6 v7.2.3 v8.0.4 v8.1.2

Signature

truncate(text, options = {}, &block)

Truncates text if it is longer than a specified :length. If text is truncated, an omission marker will be appended to the result for a total length not exceeding :length.

You can also pass a block to render and append extra content after the omission marker when text is truncated. However, this content can cause the total length to exceed :length characters.

The result will be escaped unless escape: false is specified. In any case, the result will be marked HTML-safe. Care should be taken if text might contain HTML tags or entities, because truncation could produce invalid HTML, such as unbalanced or incomplete tags.

Options

:length

The maximum number of characters that should be returned, excluding any extra content from the block. Defaults to 30.

:omission

The string to append after truncating. Defaults to "...".

:separator

A string or regexp used to find a breaking point at which to truncate. By default, truncation can occur at any character in text.

:escape

Whether to escape the result. Defaults to true.

Examples

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>")
# => "&lt;p&gt;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 world...<a href=\"#\">Continue</a>"

Parameters

text req
options opt = {}
block block
Source
# File actionview/lib/action_view/helpers/text_helper.rb, line 121
      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 121 · View on GitHub · Improve this page · Find usages on GitHub

Defined in ActionView::Helpers::TextHelper

Type at least 2 characters to search.

↑↓ navigate · open · esc close