Read more

When you want to format only line breaks, you probably do not want `simple_format`

Arne Hartherz
April 19, 2018Software engineer at makandra GmbH

For outputting a given String in HTML, you mostly want to replace line breaks with <br> or <p> tags.
You can use simple_format, but it has side effects like keeping some HTML.

Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot

If you only care about line breaks, you might be better off using a small, specialized helper method:

def format_linebreaks(text)
  safe_text = h(text)
  paragraphs = split_paragraphs(safe_text).map(&:html_safe)

  html = ''.html_safe
  paragraphs.each do |paragraph|
    html << content_tag(:p, paragraph)
  end
  html
end

Full disclosure: Under the hood this uses the private Rails helper method split_paragraphs that simple_format uses.
While it might break when upgrading Rails, you at least don't need to re-implement that part.

  • Note that calling map(&:html_safe) is okay because we escaped the input, and because splitting it won't turn the escaped input unsafe.
  • Note that simple_format has the niceness to replace &quot; with " for you

Alternative

You can also use the CSS property white-space: pre-wrap Show archive.org snapshot .

Posted by Arne Hartherz to makandra dev (2018-04-19 15:28)