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?
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
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 %>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With