Forcing HTML Escaping in Rails 3 -
i'm running issue rails auto-escaping. thinks string html_safe (which is), display purposes need still escape html. here's steps string taking.
my_string = render(:partial => "set_string", :locals => {:item => @item}) <%= my_string %> and partial basically
<h2>page header</h2> <strong><%= item.name %></strong> <%= item.body %> etc my understanding because i'm displaying text in view directly (the h2, etc) assumes safe, , escapes item outputs, makes whole my_string safe. so, when try display the
<%= my_string %> it doesn't escape remaining html. tried adding h force escaping didn't work.
so question is, there anyway force html escaping of safe string other calling on string make unsafe?
thanks lot help.
escape activesupport::safebuffer in rails 3+
in instance <%= my_string.to_str %> double-escape required.
safebuffer workings
when string escaped rails activesupport::safebuffer. point, escaping skipped because safebuffer html_safe?. it's clever solution! there times though, wish escape such cleverness.
why double-escape?
i needed re-escape content generated tag helpers pass generated markup data- attributes. has come in handy displaying template-generated code.
force-escape string that's html_safe?
call to_str on safebuffer, returns 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 # escaped string re-escaped when used in template the to_s gotcha
the to_s method looks to_str method. don't use to_s here, actionview::safebuffer#to_s returns self, to_str called above safebuffer context, returning naturally unsafe string.
Comments
Post a Comment