Preserve newline in text area with Ruby on Rails
An easier (and dare I say better) way to handle this is to apply this CSS style to the paragraph or similar HTML element that you use to display user input inside of.
white-space: pre-wrap;
One advantage is this will persevere newlines just like simple_format
without adding the extra formatting that it applies, such as turning two consecutive newlines characters into a paragraph element or automatically adding newlines to the end of the content. Just switched from using simple_format
to this myself in a similar project. Way more predictable.
Newlines are actually being preserved(as \r\n
), you just don't see them in your index/show views.
In these views, call simple_format
on your post.body
field to replace \n
s with <br>
s(HTML newlines):
simple_format(post.body)
From docs:
simple_format(text, html_options = {}, options = {}) public
Returns text transformed into HTML using simple formatting rules.
Two or more consecutive newlines(\n\n) are considered as a paragraph and wrapped
in <p> tags. One newline (\n) is considered as a linebreak and a <br /> tag is
appended. This method does not remove the newlines from the text.