0

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
4

2 回答 2

1

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 } }); 
于 2013-06-17T16:14:48.903 回答
0

With the given JSON Snippet, the server side will generate the the following JavaScript tah content to bootstrap the app:

App.initialize({ data: "content":"<div>...</div>" });

Which is not valid JavaScript. You need to wrap the data key intro an object itself, like:

App.initialize({ data: { "content":"<div>...</div>" }});

so you should end up with the following server side Haml:

- content_for :javascript do
  - javascript_tag do
    App.initialize({ data: { #{@data.to_json.html_safe } } }); 
于 2013-06-15T09:06:08.360 回答