Reputation: 75
I have a description text field in my Model. No I want to add this description on the show page. But the text renders ugly because of no linebreaks.
If i replace them with <br/>
then the rails escape them with.
So i tried to use the raw() method.
I want to escape bad HTML but have the linebreaks in my output.
I end up with some ugly code.
raw(h(@place.description.gsub("\n","#linebreak#")).gsub("#linebreak#","<br/>"))
Do you have any suggestions?
Upvotes: 4
Views: 9151
Reputation: 13181
3 years later, but it's never too late to provide a good working solution
This will escape all HTML chars but the newlines (compatible Linux, Windows and Mac)
html_escape(@place.description).gsub(/(?:\n\r?|\r\n?)/, '<br />').html_safe
Upvotes: 3
Reputation: 1051
Here's a solution that works:
<%= sanitize(@place.description.gsub("\n", "<br />"), :tags => %w(br), :attributes => %w()) %>
More reading:
Parsing newline characters in textareas without allowing all html tags
Documentation:
http://api.rubyonrails.org/classes/ActionView/Helpers/SanitizeHelper.html
From sanitize:
This sanitize helper will html encode all tags and strip all attributes that aren’t specifically allowed.
It also strips href/src tags with invalid protocols, like javascript: especially. It does its best to counter any tricks that hackers may use, like throwing in unicode/ascii/hex values to get past the javascript: filters. Check out the extensive test suite.
You can specify allowed tags with :tags option, and attributes with :attributes option.
Upvotes: 1
Reputation: 166
you should use the simple_format helper:
<%= simple_format @place.description %>
http://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html#method-i-simple_format
Upvotes: 15
Reputation: 150986
is what you are looking for
@place.description.html_safe.gsub("\n", '<br/>')
? But on second thought, doesn't the html_safe
usage like that make it easy for the site to get XSS attack? (because it assumes the description
is safe).
So won't a better solution be
<%= (h @place.description).gsub("\n", '<br/>') %>
at first I thought
<%= (h @place.description).gsub("\n", '<br/>'.html_safe) %>
is needed but actually both versions work. I then tested by adding some HTML tags to description
and it got escaped into <
etc, so it does prevent XSS attack.
Upvotes: 2