#324 Passing Data to JavaScript
There are a variety of ways to pass variables from a Rails application to JavaScript. Here I show three techniques: a script tag, a data attribute, and the Gon gem.
- Download:
- source code Project Files in Zip (87.5 KB)
- mp4 Full Size H.264 Video (14.6 MB)
- m4v Smaller H.264 Video (7.43 MB)
- webm Full Size VP8 Video (9.2 MB)
- ogv Full Size Theora Video (16.3 MB)
Browse_code
Browse Source Code
Resources
Script Tag
products/index.html.erb
<%= javascript_tag do %> window.productsURL = "<%=j products_url %>"; window.products = <%=raw Product.limit(10).to_json %>; <% end %>
app/assets/javascripts/products.js.coffee
jQuery -> alert productsURL
Data Attribute
products/index.html.erb
<%= content_tag "div", id: "products", data: {products: Product.limit(10)} do %> Loading products... <% end %>
app/assets/javascripts/products.js.coffee
jQuery -> alert $('#products').data('products')
Gon
Gemfile
gem 'gon'
layouts/application.html.erb
<%= include_gon %>
products_controller.rb
def index gon.products = Product.limit(10) # or gon.rabl "app/views/products/index.json.rabl", as: "products" end
products/index.json.rabl
collection Product.limit(10) attributes :id, :name, :price
app/assets/javascripts/products.js.coffee
alert gon.products if gon
loading