[Java] [Rails 5] How to use gem gon ~ How to pass variables from Rails to JS ~

1 minute read

Implemented functions

Development environment

ruby> 2.6.5
rails >5.2.4.2
gon> 6.3.2

This time, simply pass the variable defined in Rails Controller to JS and display it in html. It may be smoother to write in the hoge.js.erb format that is standardly installed in Rails or coffeescript, but I thought that it is a Gem that can be used as a workaround when it can not be displayed well, so I will introduce it. ..

※Note Since the variable itself is displayed in the html source according to the Gem specifications, it is better not to use it for something that needs to be hidden for security.

Introduction method

First, add to Gemfile

Gemfile


gem'gon'

And install

Terminal


$ bundle install

Write code in View of Rails This time it is supposed to be used on all pages, but it is OK if it is described in the required view. As with loading JS, the behavior differs depending on the loading timing, so be careful about the loading order.

ruby:application.html.erb


...
<%= include_gon %>
<%= javascript_include_tag "application" %>
...
</body>

Now you are ready.

Pass variables

Define Gon variable in Rails Controller. However, just add gon. to the head of the variable.

Users.erb


def show
  @user = User.find(1)
  gon.username = @user.name # pass this to JS
end

Pass the variable to JS and display it in html.

ruby:index.html.erb


...
<p id="name"></p>
...

application.js


...
let name = gon.username
$('#name').html(name);
...

It is OK if it is displayed like this.

index.html


...
<p id="name">Go here</p>
...

About the display in ####html

At the beginning I talked about “I see variables in html” It is actually read like this. It has a structure that is easy to understand whether it is good or bad.

index.html


...
  <script>
    //<![CDATA[
      window.gon={};gon.username="This is it";
    //]]>
  </script>
</body>
...

Other functions

Besides simply passing variables

  • Pass array, hash
  • Read all variables

It seems that you can also use such as. Rather, this may be the bigger role of Gem. For details, please check the official page.

Gon Official https://github.com/gazay/gon