Escape String - Output rails string in Javascript [duplicate]

假装没事ソ 提交于 2019-12-20 11:30:35

问题


I'm trying to assign a string value to a javascript object in my .erb file like so:

var data = {
    'name': '<%= @product.name %>',
    ...
};

The problem is, if the value of name is Tom's small ears,

the output of data.name would be Tom&#x27;s small ears.

Is there a way to escape special characters?

I tried doing 'name': '<%= raw @product.name %>' but Uncaught SyntaxError: Unexpected identifier gets output into the console.

Doing <%= escape_javascript @product.name %> outputs Tom\&#x27;s small ears

Edit @Stefan's comment under MrYoshiji's answer worked for me.


回答1:


You can use escape_javascript() to accomplish that:

var data = {
    'name': "<%== escape_javascript @product.name %>",
    #...
};

Link: http://api.rubyonrails.org/classes/ActionView/Helpers/JavaScriptHelper.html#method-i-escape_javascript

The alias of this method is j:

 var data = {
     'name': "<%== j @product.name %>"
 }



回答2:


var data = {
   'name': '<%=j @product.name.html_safe %>',
   ...
};


来源:https://stackoverflow.com/questions/18854749/escape-string-output-rails-string-in-javascript

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