Exit HTML output but not line breaks

I have a description text box in my model. No. I want to add this description to the display page. But the text becomes ugly due to the absence of breaks.

If I replaced them with <br/> then the rails will remove them. So I tried using the raw () method. I want to avoid bad HTML, but I have lines in my release.

I end up with some ugly codes.

 raw(h(@place.description.gsub("\n","#linebreak#")).gsub("#linebreak#","<br/>")) 

Do you have any suggestions?

+4
source share
4 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

+13
source

is what you are looking for

 @place.description.html_safe.gsub("\n", '<br/>') 

? But on the other hand, does using html_safe for this site mean an XSS attack? (because it assumes the description is safe).

So the best solution would not be

 <%= (h @place.description).gsub("\n", '<br/>') %> 

at first I thought

 <%= (h @place.description).gsub("\n", '<br/>'.html_safe) %> 

but in fact both versions work. Then I tested by adding some HTML tags to the description and it got escaped &lt; etc., therefore, it prevents an XSS attack.

+2
source

3 years later, but it's never too late to offer a good working solution

This will avoid all HTML characters, but newlines (compatible Linux, Windows and Mac)

 html_escape(@place.description).gsub(/(?:\n\r?|\r\n?)/, '<br />').html_safe 
+2
source

Here is a solution that works:

 <%= sanitize(@place.description.gsub("\n", "<br />"), :tags => %w(br), :attributes => %w()) %> 

Additional Information:

Parsing newline characters in text areas without resolving all html tags

Documentation:

http://api.rubyonrails.org/classes/ActionView/Helpers/SanitizeHelper.html

From sanitation:

This sanitize html helper will encode all tags and share all attributes that are specifically allowed.

It also blocks href / src tags with invalid protocols, for example javascript: especially. It does everything possible to withstand any tricks that hackers can use, for example, throw values โ€‹โ€‹in unicode / ascii / hex to get past javascript: filters. Check out our extensive test suite.

You can specify valid tags with the option: tags and attributes with the: attributes parameter.

+1
source

All Articles