4

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?

nonopolarity
  • 146,324
  • 131
  • 460
  • 740
Henning
  • 75
  • 1
  • 6

4 Answers4

15

you should use the simple_format helper:

<%= simple_format @place.description %>

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

steffen
  • 166
  • 1
  • 3
  • It is worth noting that this is safe from xss in newer versions of rails. See: http://stackoverflow.com/questions/3137393/rails-add-a-line-break-into-a-text-area – A5308Y Nov 22 '13 at 12:58
3

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
Benjamin Bouchet
  • 12,971
  • 2
  • 41
  • 73
2

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 &lt; etc, so it does prevent XSS attack.

nonopolarity
  • 146,324
  • 131
  • 460
  • 740
1

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.

Community
  • 1
  • 1
Verdi Erel Ergün
  • 1,021
  • 2
  • 12
  • 20