Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to allow newlines in ERB output

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?

like image 677
cmwright Avatar asked Dec 04 '22 19:12

cmwright


2 Answers

You can use the simple_formatmethod.

<%= simple_format(front) %>

More here => http://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html#method-i-simple_format

like image 140
davidb Avatar answered Dec 22 '22 00:12

davidb


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 %>
like image 23
htanata Avatar answered Dec 22 '22 02:12

htanata