Using Ruby variable in Javascript (In App View)

后端 未结 3 1425
盖世英雄少女心
盖世英雄少女心 2020-12-03 19:40

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 in

相关标签:
3条回答
  • 2020-12-03 20:09

    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>
    
    0 讨论(0)
  • 2020-12-03 20:20

    Better wrap that in quotes:

    <script type="text/javascript">
      var json = "<%= @json %>";
    </script>
    
    0 讨论(0)
  • 2020-12-03 20:31

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

    0 讨论(0)
提交回复
热议问题