Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

escape HTML output but no line-breaks

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?

like image 810
Henning Avatar asked Dec 01 '22 09:12

Henning


2 Answers

you should use the simple_format helper:

<%= simple_format @place.description %>

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

like image 70
steffen Avatar answered Dec 02 '22 21:12

steffen


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
like image 29
Benj Avatar answered Dec 02 '22 21:12

Benj