instance method simple_format

Ruby on Rails 6.0.6

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

simple_format(text, html_options = {}, options = {})

Returns text transformed into HTML using simple formatting rules. Two or more consecutive newlines(\n\n or \r\n\r\n) are considered a paragraph and wrapped in <p> tags. One newline (\n or \r\n) is considered a linebreak and a <br /> tag is appended. This method does not remove the newlines from the text.

You can pass any HTML attributes into html_options. These will be added to all created paragraphs.

Options

  • :sanitize - If false, does not sanitize text.

  • :wrapper_tag - String representing the wrapper tag, defaults to "p"

Examples

my_text = "Here is some basic text...\n...with a line break."

simple_format(my_text)
# => "<p>Here is some basic text...\n<br />...with a line break.</p>"

simple_format(my_text, {}, wrapper_tag: "div")
# => "<div>Here is some basic text...\n<br />...with a line break.</div>"

more_text = "We want to put a paragraph...\n\n...right there."

simple_format(more_text)
# => "<p>We want to put a paragraph...</p>\n\n<p>...right there.</p>"

simple_format("Look ma! A class!", class: 'description')
# => "<p class='description'>Look ma! A class!</p>"

simple_format("<blink>Unblinkable.</blink>")
# => "<p>Unblinkable.</p>"

simple_format("<blink>Blinkable!</blink> It's true.", {}, sanitize: false)
# => "<p><blink>Blinkable!</blink> It's true.</p>"

Parameters

text req
html_options opt = {}
options opt = {}
Source
# File actionview/lib/action_view/helpers/text_helper.rb, line 302
      def simple_format(text, html_options = {}, options = {})
        wrapper_tag = options.fetch(:wrapper_tag, :p)

        text = sanitize(text) if options.fetch(:sanitize, true)
        paragraphs = split_paragraphs(text)

        if paragraphs.empty?
          content_tag(wrapper_tag, nil, html_options)
        else
          paragraphs.map! { |paragraph|
            content_tag(wrapper_tag, raw(paragraph), html_options)
          }.join("\n\n").html_safe
        end
      end

Defined in actionview/lib/action_view/helpers/text_helper.rb line 302 · 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