Rares R
Rares R

Reputation: 229

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. enter image description here 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;]"

enter image description here

Please help. Thank you!

Upvotes: 1

Views: 678

Answers (1)

Sebasti&#225;n Palma
Sebasti&#225;n Palma

Reputation: 33430

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

Upvotes: 2

Related Questions