开发者

How do I keep strings with numeric contents from being interpolated as numeric expressions for JavaScript in ERb

I'm passing an array from my Rails app to Javascript via a js.erb template. The thing that's killing me is trying to keep numeric strings from being interpolated as numeric expressions. I have a set of dates correlated with numbers, i.e.:

[["2010-12-01", 19], ["2010-12-02", 12], ["2010-12-03", 15], ["2010-12-04", 0], ["2010-12-05", 0], ["2010-12-06", 13], ["2010-12-07", 18]]

So, to get that into a JS array I do this:

var accData = new Array;
<%- @accepted.each do |ary| %>
  accData.push([Date.parse(<%= ary[0] %>), parseInt(<%= ary[1].count %>) ]);
<%- end %>

But when I check the value of ary[0]开发者_如何学Go in the JS console, I get 1997, i.e., 2010 - 12 - 01.

Any ideas?


Put your <%= ary[0] %> statement inside a pair of quotes, since <%= doesn't surround the 2010-12-01 in them. You also don't actually need parseInt either (unless you surround the ary[1].count call in quotes too):

var accData = new Array;
<%- @accepted.each do |ary| %>
  accData.push([Date.parse("<%= ary[0] %>"), <%= ary[1].count %> ]);
<%- end %>


One solution to this is to use the inspect method to produce a properly enquoted string you can use in the JavaScript itself:

var accData = new Array;
<%- @accepted.each do |ary| %>
  accData.push([Date.parse(<%= ary[0].inspect %>), <%= ary[1].count.inspect %> ]);
<%- end %>

You can also make use of the to_json method which will often return something very JavaScript friendly and handles nil to null conversion, among other things.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜