7

I have a .js.erb template and I am doing:

var foo = <%= [1,2,3] %>;
var foo2 = <%= [1,2,3].to_json %>;
var foo3 = <%= ["bar"].to_json %>;
var foo4 = <%= {:foo => "bar"}.to_json %>;

foo equals 123

foo2 equals [1,2,3]

foo3 is undefined (because the browser complains of a parse error)

foo4 is undefined (because the browser complains of a parse error)


The only way I could figure out how to get foo3 to work was to do:

var foo3 = "<%= ['bar'].to_json %>";    # foo3 => "[&quot;bar&quot;]"
foo3.replace(/&quot;/g, "\""))          # => "['bar']"  <-- looks like eval should work...
eval(foo3.replace(/&quot;/g, "\""))[0]; # => "bar" ... it works

I could not foo4 to work in this way... I tried doing:

var foo4 = <%= "{:foo => 'bar'}.to_json" %>;  # foo4 => "{&quot;foo:&quot;:&quot;bar&quot;}" %>;
foo4.replace(/&quot;/g, "\""));               # => "{"foo":"bar"}"  <-- looks like eval should work
eval(foo4.replace(/&quot;/g, "\""));           # => "Parse error"   <-- but it doesn't...

Bottom line, all this needing to use eval stuff is ridiculous-- there MUST be a better way! Can someone please enlighten me as to what it is?!?!

3
  • 2
    foo.to_json is the right way. Please show us what foo.to_json is being converted to in the js source. Commented Oct 18, 2011 at 16:19
  • If I do var foo = <%= [1,2,3].to_json %>, it works.. Inspecting foo shows a js array [1,2,3]... but If I do var foo = ["a", "b", "c"].to_json %> it says "Parse error" when I load the page and foo is undefined. Commented Oct 19, 2011 at 4:11
  • Please edit your question to add the additional info. And show us what the Javascript is as a result of the Ruby js erb file. You're just telling us "parse error" on the browser--we want to see what could not be parsed--look in the js file. Commented Oct 19, 2011 at 19:12

2 Answers 2

20

The problem was .to_json ecapes the html entities!

The solution was to do:

var foo = <%= {:lol => ["lmaonade", "rotflcopter"]}.to_json.html_safe } %>

This gives me:

{"lol": ["lmaonade", "rotflcopter"]}
Sign up to request clarification or add additional context in comments.

1 Comment

Well, it is not .to_json escaping html entities, it is erb which does that. And yes, .to_html is the way to go (even though I sometimes prefer to use raw, as in <%= raw {:lol => ["lmaonade", "rotflcopter"]}.to_json } %>
0

If you need to handle when @foo is nil, try this:

var foo = <%= (@foo.kind_of?(Array) ? $foo : [] ).to_json %>;

Converting a Ruby hash to a Javascript object is done like this:

<% hash = {:foo=>'bar'} %>
var js_hash = <%= hash.to_json %>;

1 Comment

Instead of an if you can just splat-wrap in an array: var foo = <%= [*@foo].to_json %>;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.