Print valid, non-escaped JSON in a view with Rails

前端 未结 4 582
春和景丽
春和景丽 2021-01-02 00:29

I\'ve tried everything. Every combination of the helpers raw, html_safe to_json including some attempts with ::JSON.encode

相关标签:
4条回答
  • 2021-01-02 00:45

    Since ActiveSupport 2.3.3 you have been able to do .as_json

    0 讨论(0)
  • 2021-01-02 00:55

    Try this with utility method

    var campaignData<%=h " =#{raw @campaign.to_json}" if @campaign %>;
    
    0 讨论(0)
  • 2021-01-02 01:02

    Did you try escape_javascript?

    Here is an example from the *.haml file, which I just added to test my answer.

    :javascript
      var foo=$.parseJSON("#{j @albums.to_json}")
    

    Where j is an short alias for escape_javascript.

    0 讨论(0)
  • 2021-01-02 01:03

    The problem here is with the "=" string. As it's considered unsafe, it taints the other string.

    You can probably do either:

    raw("=" + @campaign.to_json)
    

    or

    "= #{@campaign.to_json}".html_safe
    

    which are roughly the same.

    0 讨论(0)
提交回复
热议问题