简体   繁体   中英

Rails use array in HAML + Coffeescript

Hello I have the following examples, I can't figure out how to make it work in html.haml.

Example 1 ( working):

# In html.erb file
<% @my_array = ['1, '2'] %>

<script>
  window.running_cycler = new MyAwesomeClass({
    custom_data: <%= raw @my_array %>
  });
</script>

Example 2 ( not working )

# In html.haml file
- @my_array = ['1', '2']

:javascript
  window.running_cycler = new MyAwesomeClass({
    custom_data: "#{raw @my_array}" 
    # or 
    # custom_data: "#{@my_array}"
  })

This is the browser error it throws. 在此处输入图片说明 How can I make it work in html.haml file?? It seems like raw is not working at all. If I don't use 'raw' then the format it gets converted is:

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

在此处输入图片说明

Please help. Thank you!

You can use single quotes and 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM