5

Click here to load reader

Passing Rails variables to JavaScript

Embed Size (px)

Citation preview

Page 1: Passing Rails variables to JavaScript

Passing Rails Variables To

Javascriptby Jedrzej Wiśniewski

Page 2: Passing Rails variables to JavaScript

How can I do it?

pass variable as data in html element

put js script in view

use gon gem

Page 3: Passing Rails variables to JavaScript

Pass variable in html element

In HTML

#my-element{ data: { troll: @troll } }

In JS

var troll = $(‘#my-element’).data(‘troll’)

Page 4: Passing Rails variables to JavaScript

Put JS script in view

In HTML

:javascript

var troll = “#{j

@troll}”

Page 5: Passing Rails variables to JavaScript

Using Gon gem

In Gemfile

gem ‘gon’

In application.html.haml

= include_gon

In controller

gon.troll = @troll

In JS

var troll = gon.troll