14

I have a Global JSON variable in my Ruby on Rails controller. It looks like this @rails_side_json = { :name => 'Will', :age => 23 }.to_json

I want this to be assigned to my javascript variable (var javascript_side_json) which resides in my javascript file named custom.js.erb

The value in javascript_side_json variable after the assignment is done should be equivalent to me writing var javascript_side_json = {"name": "Will", "age": 23 };

I am not able to achieve this by writing var javascript_side_json = <%= @rails_side_json %>

How can I achieve this? Do I need to make changes in multiple files?

3 Answers 3

25

You are almost done. Just need to make sure your json is safe html:

var javascript_side_json = <%= @rails_side_json.html_safe %>;

or

var javascript_side_json = <%=raw @rails_side_json %>;
Sign up to request clarification or add additional context in comments.

2 Comments

This works great for me. Rails 5, erb view template, passing a signature to js to display it in a view. I am using github.com/tomichj/signature-pad-rails.
I think your explanation could be a bit misleading. You aren't making sure the JSON is safe (as in it's not sanitising). What you are doing is TELLING rails that it is safe and not to escape it. The reason this matters is if somebody sees this they might assume they can use #html_safe in order to sanitise user input. (IMHO this is a very misleading method name that rails has)
9

The JSON will be escaped by default. You can tell the view to use in the code using raw

var javascript_side_json = <%= raw @rails_side_json %>

Comments

0

The above answers didn't work for me. Therefore I'm posting a solution that is working for me.

# Rails
@server_variable = some_variable.to_json.html_safe


// Javascript
let var = JSON.parse('<%= escape_javascript(@server_variable)  %>')

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.