erb in coffee script with rails 3.1

前端 未结 5 935
野性不改
野性不改 2020-12-04 15:51

I would like to use some erb in my .coffee files, like the following example

myLatlng: new google.maps.LatLng(<%=@location.latitude %>, &l         


        
相关标签:
5条回答
  • 2020-12-04 16:25

    I agree with Ciro Centelli to leave the asset pipeline alone, especially if you are using Heroku. No doubt gon is useful if you need to many assignments, but you can also do this without a gem. In your html include

    <%= javascript_tag do %>
        window.latitude = <%=@location.latitude %>
        window.longitdue = <%= @location.longitude %>
    <% end %>
    

    and in your coffee file

    myLatlng: new google.maps.LatLng(window.latitude, window.longitude)
    

    You can often work around other needs in a similar fashion. For instance if you do not want the coffee script to trigger on an element with particular id, then in the html use erb to only add that id when you want it triggered.

    0 讨论(0)
  • 2020-12-04 16:30

    Stick to the asset pipeline when possible in Rails 4, instead of using a js.erb view.

    Pass variables to the Js using gon or some other technique discussed at: Ruby on Rails - Send JavaScript variable from controller to external Javascript asset file

    With gon:

    app/views/layouts/application.html.erb:

    <head>
      <meta charset="utf-8"/>
      <%= include_gon %>
    

    app/controllers/application_controller.rb:

    before_filter do
      gon.latitude = 0.1
      gon.longitude = 0.2
    end
    

    app/assets/javascripts/locations.js.coffee:

    myLatlng: new google.maps.LatLng(gon.latitude, gon.longitude)
    

    This method is faster because file is precompiled only once at startup, gets served by the server instead of through Rails, and on the same HTTP request as the rest of the Js.

    0 讨论(0)
  • 2020-12-04 16:31

    In Rails 3.2.8, I didn't have to move my .coffee file to /app/views. I just added .erb to the filename and left it in /app/assets/javascripts. Ie. I changed

    /app/assets/javascripts/user_answers.coffee.js to 
    /app/assets/javascripts/user_answers.coffee.js.erb
    

    and then this worked:

    # Note the level of indentation.
    var x = 2;
    
    <% Question.first(2).each do |eq| %>
    alert('eq: ' + <%= eq.id %>)
    <% end %>
    

    (The indentation level has to match in CoffeeScript, not Ruby.) Enjoy your coffee embedded in rubies.

    0 讨论(0)
  • 2020-12-04 16:37

    If you want erb in the .coffee files IN YOUR VIEW folder, leave your file named as yourfilename.js.coffee, and Rails will still process the ERB, oddly enough.

    To make it work in Heroku, move coffee-rails out of the assets group in your Gemfile.

    0 讨论(0)
  • 2020-12-04 16:39

    You may have to rename your file to locations.coffee.erb so erb is processed before coffee :)

    0 讨论(0)
提交回复
热议问题