开发者

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)}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜