代码之家  ›  专栏  ›  技术社区  ›  Rares R

Rails在HAML+Coffeescript中使用数组

  •  1
  • Rares R  · 技术社区  · 7 年前

    示例1(工作):

    # In html.erb file
    <% @my_array = ['1, '2'] %>
    
    <script>
      window.running_cycler = new MyAwesomeClass({
        custom_data: <%= raw @my_array %>
      });
    </script>
    

    # In html.haml file
    - @my_array = ['1', '2']
    
    :javascript
      window.running_cycler = new MyAwesomeClass({
        custom_data: "#{raw @my_array}" 
        # or 
        # custom_data: "#{@my_array}"
      })
    

    enter image description here 如果我不使用“raw”,则转换的格式为:

    "[&quot;1&quot;, &quot;8&quot;]"
    

    enter image description here

    请帮忙。非常感谢。

    1 回复  |  直到 7 年前
        1
  •  2
  •   Sebastián Palma    7 年前

    您可以使用单引号和 raw

    - @my_array = ['1', '2']
    
    :javascript
      window.running_cycler = { 'custom_data': '#{raw @my_array}' }
      console.log(JSON.parse(window.running_cycler.custom_data).length)
      // 2