4

Currently, I have a ruby variable accessible by the view called @json (which contains information I need in JSON format)

However, I want to pass this into a script area such as

<script type="text/javascript" charset="utf-8">
//Want @json to be usable here
</script>

Is there any way to do this?

asked Dec 2, 2012 at 19:58

3 Answers 3

6

Assuming the script tag you mentioned is in a html erb view you can just use this:

<script type="text/javascript" charset="utf-8">
var json = <%= @json || 'null' %>;
</script>
answered Dec 2, 2012 at 20:00
Sign up to request clarification or add additional context in comments.

Comments

2

Another way to do it is like this: var json = "#{ @json || 'null' }"

answered Jul 29, 2013 at 18:58

Comments

1

Better wrap that in quotes:

<script type="text/javascript">
 var json = "<%= @json %>";
</script>
answered Dec 4, 2012 at 16:48

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.