Parsing newline characters in textareas without allowing all html tags

荒凉一梦 提交于 2019-12-05 00:14:14


I have a textarea field where users can enter content. When it comes to displaying their entry on a page, rails returns \n for each line break, which appears as no break at all for html on the page.

From what I gather, the standard way of getting around this is a .gsub command, replacing \n with <br />, and then a .html_safe on the end to ensure the <br /> renders.

The problem is, I don't want to html_safe the content - html should still be replaced, but <br /> tags should be injected into the (non-escaped) content.

Suggestions appreciated.


The simple_format method is good for formatting line breaks. It wraps text blocks in <p> tags, and converts newline characters into line breaks (<br>) (double newlines breaks the following text into a second paragraph).

It doesn't however escape other html characters, and instead just allows them. For what you're after a combination of simple_format along with sanitize should do nicely. Try using this:

<%=raw sanitize(simple_format(@article.body), :tags => %w(br p) ) %>


If you want HTML tags entered in the text area visible, but still want line breaks to show, try this:

<%= simple_format(h @article.body) %>

The "h" quotes all the HTML special chars and "simple_format" then converts the line breaks to <br>.


Depending on what you want to do, you can store the \n as it is, and then, when displaying the content on screen, use (h @comment.content).gsub("\n", '<br>'), which is to first escape all HTML tags, and then replace the \n with the <br>


All this can be avoided by using &lt;pre&gt; tags. This has the advantage of preserving tabbing as well. eg

&lt;pre&gt;&lt;%= @article.body %&gt;&lt;/pre&gt;