Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can I convert ruby data structures to javascript data structures with .js.erb?

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?!?!

like image 969
patrick Avatar asked Oct 18 '11 16:10

patrick


1 Answers

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"]}
like image 96
patrick Avatar answered Sep 19 '22 02:09

patrick