Pass ruby variables to js code
Im curious what is the best way to pass my rails variables into 开发者_Go百科javascript code. For example i have this line in my controller:
@address = get_user_address
@farms = Farm.all
Now i need to use it for initialize my google map, for now im going with plain javascript and im more than sure that this is ugly solution. In view im have something like that
%script
distance = []
- @farms.each do |f|
distance.push(['#{f.latitude}' + ',' + '#{f.longitude}' + ',' + '#{f.name}', #{f.distance_from(@address)}])
distance.sort(sortMultiDimensional)
user_coords = #{Geocoder.coordinates(@address)}
And google map initalize going under. How to avoid this ugly ruby-in-javascript code? Thanks!
Place the variables into the HTML of a rendered page then use javascript to read them from the DOM at execution time. This allows you to write the JS in separate files and without cluttering the file with random script variables.
Be sure to sanitize user supplied variables.
%script
distance = #{@farms.collect{|f| [f.latitude, f.longitude, f.name] }.inspect}
distance.sort(sortMultiDimensional)
user_coords = #{Geocoder.coordinates(@address)}
精彩评论