1

I have figured out a way to do this, defining a variable inside a HTML attribute like this:

div data-name=some_var id="component"

Then from Javascript I can retrieve it:

alert($("#component").data("name"));

However, it looks very ugly to me. Is there another way to achieve this?

Sheharyar
  • 73,588
  • 21
  • 168
  • 215
lapinkoira
  • 8,320
  • 9
  • 51
  • 94
  • The only other way is through a request (additional architectural considerations) or storing it in a cookie (additional code and complexity to retrieve the value). Although I do agree that theoretically it's a bit ugly having to embed data in the html for javascript consumption, it's the simplest way and I feel a bit better about it by using `meta` tags and removing the element from the DOM after it has been read in the front-end. – m3characters Mar 12 '18 at 10:31
  • Ok, looks like this is the best solution for now, meta tags is a good idea if we have to use html tags anyway – lapinkoira Mar 12 '18 at 10:47
  • you can also define a script tag that sets it on the `window` scope – m3characters Mar 12 '18 at 11:43

2 Answers2

1

That might feel dirty to you, but that's the most efficient way of sending data to the frontend from the backend. In fact, it's pretty common.

Other ways of sending data would always involve making a separate web-request, which is usually unneeded in most cases.


And since you're using jQuery, it also abstracts away the implementation so you can send a pure JSON object in a data- attribute and can use it without having to parse it on the client-side.

div id='item' data-obj='{"foo":"bar"}'

and in your JS:

$('#item').data('obj') // {foo: bar}

Related resources:

Sheharyar
  • 73,588
  • 21
  • 168
  • 215
1

I usualy do it like this:

div id="component"
javascript:
  var templateData = {
    name: '<%= @name %>',
    product_str: '<%= Poison.encode!(@product) %>',
  };

You'll probably need to install Poison to encode data to JSON.

Klesun
  • 12,280
  • 5
  • 59
  • 52