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 or coffeescript
that comes standard with Rails, but I thought it would be a gem that can be used as a workaround when it can not be displayed well, so I will introduce it. ..
※Caution Due to the Gem specification, the variable itself is displayed in the html source, so it is better not to use it for things that need to be hidden for security reasons.
First, add to Gemfile
Gemfile
gem 'gon'
And install
Terminal
$ bundle install
Write code in Rails View 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 reading JS, the behavior differs depending on the reading timing, so be careful about the reading order.
ruby:application.html.erb
・ ・ ・
<%= include_gon %>
<%= javascript_include_tag "application" %>
・ ・ ・
</body>
You are now ready.
Define a variable for Gon in Rails Controller.
All you have to do is prefix the variable with gon.
.
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);
・ ・ ・
If it is displayed like this, it is OK.
index.html
・ ・ ・
<p id="name">Kohei</p>
・ ・ ・
At the beginning, I talked about "variables can be seen in html". It is actually loaded like this. The structure is easy to understand, good or bad, isn't it?
index.html
・ ・ ・
<script>
//<![CDATA[
window.gon={};gon.username="Kohei";
//]]>
</script>
</body>
・ ・ ・
Besides simply passing variables
--Pass an array and hash --Read all variables
It seems that you can also use it. Rather, this may be a bigger role for Gem. Please check the official page for details.
** Gon Official ** https://github.com/gazay/gon
Recommended Posts