Reputation: 3426
I'm trying to show the contents of a field from the database in a <p>
element. In the html.erb template the code looks like:
<p><%= front.gsub(/(\r)?\n/, "<br>") %></p> ...
The issue I'm having is that to escape the breaks, I have to apply the .html_safe
method at the end of the above gsub, but doing so opens the whole application to XSS attacks. How can I only allow the breaks to be escaped?
Upvotes: 5
Views: 7619
Reputation: 50057
Have you considered wrapping the text into <pre>
-tags instead? That will keep the basic formatting (newlines, spaces, ...).
Upvotes: 2
Reputation: 36944
This is based on the simple_format
helper. We can use sanitize
to remove bad tags that allow XSS attacks.
<%= sanitize(front).gsub(/(\r)?\n/, "<br/>").html_safe %>
You can also use strip_tags if you want to remove all HTML tags before replacing new lines with <br>
.
<%= strip_tags(front).gsub(/(\r)?\n/, "<br/>").html_safe %>
Upvotes: 2
Reputation: 8954
You can use the simple_format
method.
<%= simple_format(front) %>
More here => http://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html#method-i-simple_format
Upvotes: 13