Having this code in a view partial of type .js.coffee (it’s being rendered as a view, not as an asset) :
<% if @followed_car_ids.present? %>
for car_id_and_path in <%= @followed_car_ids_and_paths.to_json %>
toggle_follow(car_id_and_path[0], true, car_id_and_path[1])
<% end %>
In the controller:
@followed_car_ids_and_paths = @followed_cars.map{|car| [car.id, url_for(current_user.car_subscriptions.find_by_car_id(car))]}
Note that it doesn’t matter if I put the map (or collect) in the view. Doesn’t work either if I put a simple string instead of url_for(....
It gives this error:
ActionView::Template::Error (Error: Parse error on line 1: Unexpected 'LOGIC'):
1: <% if @followed_car_ids.present? %>
2: for car_id_and_path in <%= @followed_car_ids_and_paths.to_json %>
3: toggle_follow(car_id_and_path[0], true, car_id_and_path[1])
4: <% end %>
app/views/general_ajax/_update_followed_cars.js.coffee:1:in `_app_views_general_ajax__update_followed_cars_js_coffee__3478461849674996439_70355260673980'
When I remove the = from <%= on line 2 and add some kind of dummy array before the error stops:
for car_id_and_path in [1,2,3] <% @followed_car_ids_and_paths.to_json %>
The error doesn’t occur if I use a flat array (not doubled with map):
for car_id_and_path in <%= @followed_car_ids %>
Neither when it’s like this:
for car_id_and_path in [[1, 'a'],[2, 'b'],[3, 'c']]
I had the same issue with parsing a instance variable to json using
to_jsonin my coffeescript file.I resolved the issue by appending
html_safeto the line:@instance_var.to_json.html_safe