Use ruby variables in javascript.

There seem to be various methods, but the method I used this time.

Conclusion

index.html.erb



@test = { 'hoge' => 'huga', 'hogehoge' => 'hugahuga' }

<div id="hoge" data-hoge-id="<%= @test.to_json %>"></div>

<script>
  var test = $('#hoge').data('hoge-id');
</script>

That was all.

It can also be implemented using a gem called "gon".

Recommended Posts

Use ruby variables in javascript.
Use "Rhino" which runs JavaScript in Java
Variables / scope (ruby)
Heavy in Ruby! ??
How to use environment variables in RubyOnRails
Use Interceptor in Spring
Use OpenCV in Java
Use MouseListener in Processing
Use images in Rails
Output triangle in Ruby
Use PostgreSQL in Scala
Variable type in ruby
Use PreparedStatement in Java
Fast popcount in Ruby
Use variables for class and id names in haml
Handling of date and time in Ruby. Use Date and Time properly.
Multiplication in a Ruby array
About regular expressions in Ruby
Rbenv command to use Ruby
Ruby: How to use cookies
How to use Java variables
Use multiple checkboxes in Rails6!
Use Ruby with Google Colab
NCk mod p in Ruby
Pass the i18n locale to JavaScript
Ruby on Rails Japanese-English support i18n
[Java] Do not use "+" in append!
Use composite keys in Java Map.
Use the Findbugs plugin in Eclipse
[Processing × Java] How to use variables
Implement a gRPC client in Ruby
Write keys and values in Ruby
How to use InjectorHolder in OpenAM
[Super Introduction] About Symbols in Ruby
[Ruby] Handle instance variables with instance methods
Hanachan in Ruby (non-destructive array manipulation)
How to use classes in Java?
How to name variables in Java
Use completion in Eclipse on mac
Address already in use workaround (Windows)
Setting project environment variables in intelliJ
openssl version information in ruby OPENSSL_VERSION
How to use Ruby inject method
Ruby methods often used in Rails
[Ruby] Display the contents of variables
Do you use Stream in Java?
Make Ruby segfault in two lines
I tried to make full use of the CPU core in Ruby
[Ruby / Rails] Use alias. In a way that rubocop won't get angry!