Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 283
Jonathan Avatar asked Feb 19 '23 07:02

Jonathan


1 Answers

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>
like image 119
Trent Earl Avatar answered Feb 21 '23 02:02

Trent Earl