Forcing HTML Escaping in Rails 3

拈花ヽ惹草 提交于 2019-12-03 11:58:21

Escape from ActiveSupport::SafeBuffer in Rails 3+

In this instance <%= my_string.to_str %> will double-escape as required.

SafeBuffer workings

When a string is escaped by Rails you get an ActiveSupport::SafeBuffer. From that point, extra escaping is skipped because the SafeBuffer is html_safe?. It's a clever solution! There are times though, that we wish to escape such cleverness.

Why double-escape?

I needed to re-escape content generated by tag helpers to pass generated markup to data- attributes. This has also come in handy for displaying template-generated code.

Force-escape for a String that's html_safe?

Call to_str on the SafeBuffer, which returns a String.

# Example html safe content
content = content_tag :code, 'codez<>'
content.html_safe? # true

# call .to_str
escaped = content.to_str
escaped.html_safe? # false

# The escaped String will now be re-escaped when used in a template

The to_s gotcha

The to_s method looks very much like the to_str method. Don't use to_s here, ActionView::SafeBuffer#to_s just returns self, where to_str is called above the SafeBuffer context, returning a naturally unsafe String.

Thanks to Sebastien for the suggestion, I wanted to get the real answer here and not buried in the comments:

I looks like this works:

<%= raw CGI::escapeHTML(my_string) %>

You need the "raw" call otherwise the escapeHTML makes the string unsafe in addition to escaping it so the auto escape double escapes it.

To interpret the html (it's what i understood you need), you have to use :

<%= raw my_string %>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!