Method: ActionView::Helpers::TextHelper#simple_format

Defined in:
actionview/lib/action_view/helpers/text_helper.rb

#simple_format(text, html_options = {}, options = {}) ⇒ Object

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.

  • :sanitize_options - Any extra options you want appended to the sanitize.

  • :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>"

simple_format("<a target=\"_blank\" href=\"http://example.com\">Continue</a>", {}, { sanitize_options: { attributes: %w[target href] } })
# => "<p><a target=\"_blank\" href=\"http://example.com\">Continue</a></p>"


383
384
385
386
387
388
389
390
391
392
393
394
395
396
# File 'actionview/lib/action_view/helpers/text_helper.rb', line 383

def simple_format(text, html_options = {}, options = {})
  wrapper_tag = options[:wrapper_tag] || "p"

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

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