0

I have created index.html.erb file and had ruby/html code in it and file is running on webrick server at localhost without using rails .

I have a Global JSON variable in my Ruby code. It looks like this :

@ruby_side_json = [{ :name => 'Will', :age => 23 },{ :name => 'John', :age => 30 }].to_json

I want this to be assigned to my javascript variable which resides in script

Not succeed by writing : var javascript_side_json = <%= @ruby_side_json %>

How can I achieve this?

6
  • What error do you get? Commented Aug 2, 2016 at 12:19
  • what do you see in browser console, when you type javascript_side_json? Commented Aug 2, 2016 at 12:25
  • [Object{ :name => 'Will', :age => 23 },Object{ :name => 'John', :age => 30 }] Commented Aug 2, 2016 at 12:31
  • Try.. var javascript_side_json = JSON.parse(<%= @rails_side_json %>); Commented Aug 2, 2016 at 12:35
  • 1
    In general, instead of using inline javascript, you might want to pass the json to some meta-tag / data attribute, e.g. in your application layout <meta js-side-json="<%= @rails_side_json %>">. There is also a gem called gon github.com/gazay/gon which does essentially the same but via a more convenient api. Commented Aug 2, 2016 at 13:01

3 Answers 3

1

If you are using rails tag inside script tag, it should be quoted with single or double quotes.

Change your code as given below :

var javascript_side_json = '<%= @rails_side_json %>';

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

Comments

0

In the environment you describe, the only way I can see that working, is by creating a <script> tag directly in the html and rendering it at the top, before any javascript require tags.

like this:

<head>
  <script>
    var javascript_side_json = <%= @rails_side_json %>
  </script>
</head>

That said, it's kinda ugly, but it should work; if you don't place it before the JS require tags, then the data won't be there when you try to execute some JS that needs it.

Comments

0

Assuming that you're not using Rails, and JSON is being generated properly with your to_json implementation. Then try doing this:

<script>    
  var javascript_side_json = <%= @rails_side_json %>;
</script>

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.