4

I have a rails application which is serving up a number of views which include specific data from the database to be manipulated by some javascript, specifically for use with Chartjs.

Options I have explored are:

  1. Use an ajax call to pull the data off the server. I don't like this one because the user isn't changing any data, I have access to all the data when I render the page, there ought to be a better way.
  2. Use <script> tags in the view ERB and simply have ERB interpolate the variable. This seems a little hacky and definitely doesn't take advantage of all my beautiful haml. But it is easy and allows me to put javascript variables on the page which can then be picked up after the document.onload.
  3. Gon. Great gem and very easy. But should this really require a gem?

I feel as though the solution should involve the asset pipeline and some sort of rails interpolation, but I can't seem to make that work very cleanly. What is the elegant rails 4 way for solving this?

Thanks everyone!

2
  • 3
    There's no better way... Just personal taste ; I personally use GON (a lot with RABL or just by itself). The gem makes pushing json data to the client a breeze, without any overhead. So yeah, it's worth it. Commented Mar 8, 2014 at 19:06
  • Did you consider checking out JavaScript filter? haml.info/docs/yardoc/file.REFERENCE.html#javascript-filter Could you please give an example? This might help understanding the issue better. Commented May 10, 2015 at 1:15

1 Answer 1

0

There are many ways to pass data from server-side to javascript, I'll list two of the most common (that don't use a gem or other external tools) below:

  1. Use the second method you described, and interpolate ERB tags inside the javsacript. This is ugly, hacky and is not even close to best practice.

  2. Use data attributes. You can modify your HAML to include additional attributes, like "data-my-variable", and access it via javascript (example using jQuery: $(element).data("my-variable")).

The data attribute method is, in my opinion, the cleanest way of doing this, it's exactly the purpose of data attributes.

Now, I don't know HAML, I've only worked with ERB before, but I found this answer by Mandeep, which explains how you can add data attributes to your HAML:

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

OR

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

EDIT: Sorry, I found your question along with other, newer, questions, I just assumed it was recent, and not from over a year ago :)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.