Parsing newline characters in textareas without allowing all html tags
Asked Answered
A

4

5

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.

Apron answered 23/11, 2010 at 7:23 Comment(0)
P
16

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) ) %>

Pep answered 23/11, 2010 at 7:54 Comment(4)
Or even better yet, user the builtin h() method: <%=simple_format h @article.body %>Birthstone
If you want to do this in a model or controller: ActionController::Base.helpers.raw ActionController::Base.helpers.sanitize((ActionController::Base.helpers.simple_format( body )), :tags => %w(br p) )Phosphorate
how to allow only "br"? If I add it, it doesn't allow multiple "br" linesHaunting
Just for those seeing this now, it appears that simple_format sanitizes by default now. api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.htmlMarrero
N
6

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>.

Nutmeg answered 31/1, 2011 at 9:23 Comment(0)
S
2

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>

Supination answered 23/11, 2010 at 7:39 Comment(0)
P
0

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;
Photofluorography answered 1/8, 2014 at 5:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.