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?

3
  • 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. Commented Mar 12, 2018 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 Commented Mar 12, 2018 at 10:47
  • you can also define a script tag that sets it on the window scope Commented Mar 12, 2018 at 11:43

2 Answers 2

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:

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

Comments

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.

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.