How to enable ruby ​​variables in javascript in Rails 4?

I have a rails application that serves several views that include specific data from a database that some javascript will handle, especially for use with Chartjs.

The options I learned are as follows:

  • Use the ajax call to pull data from the server. I don’t like it, because the user does not change any data, I have access to all the data when rendering the page, there should be a better way.
  • Use tags <script>in the ERB view and just use ERB to interpolate the variable. It seems a bit hacked and certainly does not use all my beautiful hamles. But this is easy and allows me to put javascript variables on the page, which can then be obtained after document.onload.
  • Gon. Big gem and very light. But if it really requires a gem?

It seems to me that the solution should include an asset pipeline and some rail interpolation, but I cannot get this work to work very cleanly. What are the elegant rails to solve this problem?

Thanks everyone!

+4
source share
1 answer

javascript, ( ) :

  • , , ERB javsacript. , .

  • . HAML, , "data-my-variable", javascript ( jQuery: $(element).data("my-variable")).

- , , , .

HAML, ERB , Mandeep, , HAML:

%a{"data-my-variable" => "my data", href: "#"}

%a{href: "#", :data => {:my_variable => "my data"}}

EDIT: , , , , , , :)

0

Source: https://habr.com/ru/post/1530265/


All Articles