Is there a way of attaching data to elements in Rails like jQuery. For instance if you have
var element = $('element');
element.data('i', 'Hello world');
in jquery, you can retrieve that data later:
console.log(element.data('i));
will result in
Hello world
this way it stores the information in an obscure place resulting in a variable that isn't accessible from outside of jQuery directly.
In contrary, right now I'm only aware of appending HTML data attributes using Rails:
<%= content_tag(:div, "Something", data: { i: 'Hello world' }) %>
Which is equivalent of setting a .attr() in jQuery.
Setting HTML data attributes results in:
So essentially, what I'm trying to ask here is, can I append jQuery data set with Rails so it will be:
.data()Is there a way of attaching data to elements in Rails like jQuery
Example:
# in your view *.html.erb
<%= content_tag(:div, "Content", data: { whatever: 42, whenever: "5pm" }) %>
Results in:
<div data-whatever="42" data-whenever="5pm">Content</div>
Have a look at gon, which makes it trivially simple to access your Rails variables in JavaScript. It doesn't attach them as data attributes, but at the same time you are sending the data to the client all in one go, so it will be available in the page source.
(This Railscast episode also walks you through the setup, and how it works)
If you really need the data to be hidden/obfuscated (I assume this is from scrapers, so that's what I'll focus on here), and you don't want to do this client side, then you'll need to set up a new route in your Rails application, and do AJAX calls to that endpoint to return the data. It's not foolproof, but there's options here to make things a bit more difficult for scrapers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With