LoginSignup
0
1

More than 3 years have passed since last update.

【gon】jsでRails変数を取得する

Last updated at Posted at 2020-01-25

Railsでjsライブラリを使うときに楽にRailsで定義した変数をJavaScriptに渡したい!楽したい!

プログラマ三大美徳

1.怠慢(Laziness)
2.短気(Impatience)
3.傲慢(Hubris)

まさにこれですね。

何を使うか?

RailsといえばGemですね。[gon]というgemです。
https://github.com/gazay/gon

インストール

Gemfileに記載

Gemfile
gem 'gon'

ターミナルからインストール

ターミナル
bundle install

読み込み設定

application.html.erb
<%= include_gon %>
<%= javascript_include_tag "application" %>

使ってみる

****.controller.rb
gon.user_name = 'my name is imaizumi'
****.js
console.log(gon.user_name)

スクリーンショット 2020-01-25 21.11.28.png

バッチリ変数を渡せました:yum:

0
1
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
0
1