开发者

Sprockets not properly porcessing erb in js file

开发者 https://www.devze.com 2023-03-24 02:44 出处:网络
i have a simple gmaps V3 api call to produce a static map based on a lat/lon in the location record. the file reisdes in the asset/javascripts dir, and is named location_static_map.erb.js

i have a simple gmaps V3 api call to produce a static map based on a lat/lon in the location record. the file reisdes in the asset/javascripts dir, and is named location_static_map.erb.js

here's the code:

var location;
function initialize() {
  var myOptions = {
    zoom: 10,
    mapTypeId: google.maps.MapTypeId.HYBRID
  };
  var map = new google.maps.Map(document.getElementById("location_static_map"), myOptions);
  var lat = <%= "#{@location.latitude}" %>;
  var lon = <%= "#{@location.longitude}" %>;
  location = lat,lon;
  map.setCenter(location);
  var marker = new google.maps.Marker({
    position: location,
    map: map,
    visible: true,
    draggable: false,
    title: "Your Location is Here..."
  });
}

i am getting a Syntax parse error on the embedded erb code. note that i have other dynamic maps built against the V3 api that are working fine so this is def an issue with the embedded erb evaluation....also note that i have tried the filename exte开发者_Go百科nsion as .js.erb under the assumption that i had the processing order wrong, but that resulted in an undefined method error for 'latitude' as it hit the first line of the erb code....

also note that the parse error is occurring in the generated application.js file

any input appreciated.....


It is my understanding that when you release this code to production you will 'compile' all of your js assets into a single application.js file - the erb will be evaluated at that time and NEVER again. In development this is not an issue as the application.js is compiled on every request. From looking at your code I assume you want the @location values to change with each request, your current approach is not going to work.

as far as the errors you are receiving, is it a sprokets parse error or a client side javascript error? guessing @location is nil when the js.erb is being processed?

you might want to wrap this code up into a reusable javascriopt function/object and then set the instance variables in the view when calling the client side code? That call could look something like this

<script>
window.App.Locator.initialize('<%= @location.latitude %>', '<%= @location.longitude %>');
</script>

with this code in the view itself, the erb will be re-evaluated on each request, even in production

0

精彩评论

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

关注公众号