RailsCasts - Ruby on Rails Screencasts

RailsCasts Pro episodes are now free!

Learn more or hide this

Passing Data to JavaScript

#324 Passing Data to JavaScript

Feb 13, 2012 | 6 minutes | Views, Plugins
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.
Click to Play Video ▶
Tweet
  • 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

AltStyle によって変換されたページ (->オリジナル) /