开发者

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 t开发者_开发百科ried 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?


you should use the simple_format helper:

<%= simple_format @place.description %>

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


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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜