How to pass a javascript variable into a erb code in a js view?

前端 未结 8 2045
时光取名叫无心
时光取名叫无心 2020-11-27 06:19

I have this Javascript view in my Rails 3 project:

app/views/expenses/new_daily.js.erb

var i = parseInt($(\'#daily\').attr(\'data-num\')) + 1;
//$(\'         


        
8条回答
  •  余生分开走
    2020-11-27 06:43

    1) You may create a js tag with global variable in you erb template, after that you will be able to access that variable from any js file

    <%= javascript_tag do %>
       window.productsURL = '<%= j products_url %>';
    <% end %>
    

    2) You can pass data to data-attribute in erb template and access it by js on client side that way $('#products').data('products')

    <%= content_tag "div", id: "products", data: {products: Product.limit(10)} do %>
       Loading products...
    <% end %>
    

    3) You can use gon, to use your Rails variables in your js

    There is a good article, read it and fine solution for your specific case http://railscasts.com/episodes/324-passing-data-to-javascript, more comments are here http://railscasts.com/episodes/324-passing-data-to-javascript?view=asciicast

提交回复
热议问题