Ruby Every cycle in slim-lang

I want to be able to scroll through a var instance through javascript, but I'm not quite sure how to make it work.

javascript: -@spots.each do |spot| map.addMarker({ lat: "#{spot.latitude}", lng: "#{spot.longitude}", title: "spot", }); }); 

What I tried: Using <% @ spot.each do | spot | %> and without quotes for # {}

+6
source share
2 answers

It seems that once you find yourself in javascript: slim-block, you also will not be able to execute ruby ​​loop.

I was able to get this to work mostly

 - @spots.each do |spot| javascript: map.addMarker({ lat: #{spot.latitude}, lng: #{spot.longitude}, title: "spot" }); 

but it makes separate script tags for each addMarker call, which seems pretty dumb.

You can also try placing the data on the page as JSON and then looping through Javascript. Something like that:

 javascript: var spots = #{raw @spots.to_json}; var ii = 0; var nspots = spots.length; for(;ii<nspots;++ii) { theMap.addMarker(spots[ii]); } 

You want theMap be available by the time this file is theMap , but I think this can do the trick. You should also check the JSON format for each @spot. Depending on how you configure JSON, each spot may look like

 {'spot': { 'latitude': ###, 'longitude': ### } } 

which means you have to play the object in a loop.

+8
source

easy to fix, but not effective if spots are too long.

 -@spots.each do |spot| javascript: map.addMarker({ lat: "#{spot.latitude}", lng: "#{spot.longitude}", title: "spot", }); 

2. loop in js instead of view context

 javascript: var spots = #{@spots.to_json}; $(spots).each(function(index, obj) { map.addMarker({ lat: obj.latitude, lng: obj.longitude, title: "spot", }); }); 
+2
source

Source: https://habr.com/ru/post/957757/


All Articles