Jonathan
Jonathan

Reputation: 1469

Using Ruby variable in Javascript (In App View)

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?

Upvotes: 4

Views: 10692

Answers (3)

Christian
Christian

Reputation: 859

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

Upvotes: 2

Samo
Samo

Reputation: 8240

Better wrap that in quotes:

<script type="text/javascript">
  var json = "<%= @json %>";
</script>

Upvotes: 1

Trent Earl
Trent Earl

Reputation: 3607

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>

Upvotes: 6

Related Questions