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.
[Docker] Use environment variables in Nginx conf
Use "Rhino" which runs JavaScript in Java
Variables / scope (ruby)
Use selenium (Firefox) in Ruby in WSL environment
Heavy in Ruby! ??
Use selenium (Chrome) in Ruby in WSL environment
How to use environment variables in RubyOnRails
About Ruby variables
I want to use arrow notation in Ruby
[Ruby] Assign variables in conditional expressions in if statements.
About eval in Ruby
Use java.time in Jackson
Use Interceptor in Spring
Use OpenCV in Java
Use MouseListener in Processing
Use images in Rails
Ruby variables and methods
Output triangle in Ruby
Use PostgreSQL in Scala
Variable type in ruby
Use PreparedStatement in Java
Fast popcount in Ruby
How to embed JavaScript variables in HTML with Thymeleaf
[Ruby] How to use standard output in conditional branching
Use variables for class and id names in haml
Use Coveralls with GitHub Actions in a Ruby repository
Handling of date and time in Ruby. Use Date and Time properly.
ABC177 --solving E in Ruby
Validate JWT token in Ruby
Implemented XPath 1.0 parser in Ruby
Read design patterns in Ruby
Write class inheritance in Ruby
Try calling JavaScript in Java
How to use Ruby return
Use C program from Ruby
Integer unified into Integer in Ruby 2.4
Multiplication in a Ruby array
About regular expressions in Ruby
Rbenv command to use Ruby
Ruby: How to use cookies
Birthday attack calculation in Ruby
How to use Java variables
Use Redis Stream in Java
Ruby study notes (variables & functions)
Judgment of fractions in Ruby
Find Roman numerals in Ruby
Try using gRPC in Ruby
Use multiple checkboxes in Rails6!
Use Ruby with Google Colab
Ruby variables and functions (methods)
[Ruby] Find numbers in arrays
NCk mod p in Ruby
Chinese Remainder Theorem in Ruby
[Ruby] This is the solution. When should I use instance variables?
[Ruby] Use an external API that returns JSON in HTTP request
How to use Lombok in Spring
Sorting hashes in a Ruby array
Basics of sending Gmail in Ruby
Pass the i18n locale to JavaScript
How to iterate infinitely in Ruby