I have an app that has page content that includes script tags, but when it tries to render it gives the error 'Uncaught SyntaxError: Unexpected token ILLEGAL'.
I'm initializing a backbone app as follows:
- content_for :javascript do
- javascript_tag do
App.initialize({ data: #{@data.to_json.html_safe } });
which generates the following JSON:
<script type="text/javascript">
//<![CDATA[
App.initialize({ data: {"content":"<div style=\"padding-left:5px;\"><script type=\"text/javascript\" src=\"http://www.opentable.com/frontdoor/default.aspx?rid=52900&restref=52900&bgcolor=8AA86B&titlecolor=0F0F0F&subtitlecolor=0F0F0F&btnbgimage=http://www.opentable.com/frontdoor/img/ot_btn_black.png&otlink=FFFFFF&icon=light&mode=short&hover=1\"></script></div>"});
//]]>
</script>
I'm trying to render it as follows (with hamlc):
- if @page.attributes.content
.text.page-content~ @page.attributes.content
With the help of Chad from Thoughtbot.com, I was pointed to the following blog post. Apparently this is a "flaw" with json escaping. http://jfire.io/blog/2012/04/30/how-to-securely-bootstrap-json-in-a-rails-view/
First override the json function.
config/initializers/json_escape.rb
class ActionView::Base
def json_escape(s)
result = s.to_s.gsub('/', '\/')
s.html_safe? ? result.html_safe : result
end
alias j json_escape
end
(restart your server)
And in your rails view use the j
function before your ruby code:
- content_for :javascript do
- javascript_tag do
App.initialize({ data: #{j @data.to_json.html_safe } });