19
14

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Railsの変数をJSで使う(gon、Rails 5)

Last updated at Posted at 2018-05-10

gazay/gon: Your Rails variables in your JS
https://github.com/gazay/gon

検証環境

検証日: 2018/05/10
debian 9.4
rails 5.1.5
Bundler version 1.16.1
gon v6.1.0

手順

1. gemの追加

Gemfile
gem 'gon'
bundle install

2. テンプレートに記述

JSファイルよりも前に記述する

app/views/layouts/application.html.erb
<%= Gon::Base.render_data %>

3. Controllerに変数をセット

def index
  gon.str = 'Hello World'
end

4. JSから読み込む

application.js
console.log(gon.str);

仕組み

gonがHTMLにグローバル変数を宣言してくれてました。

<script>
//<![CDATA[
window.gon={};gon.str="Hello World";
//]]>
</script>
19
14
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
19
14

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?