11

I have a Twig array and I want to send it to JavaScript:

<script>
    var packages = {{packages}}
</script>

Error! Array to String Conversion.

How should I do that?

Peyman Mohamadpour
  • 17,954
  • 24
  • 89
  • 100
ehsan
  • 209
  • 1
  • 4
  • 13

4 Answers4

29

I have an array from twig named filters, this single line did the job

const filters = JSON.parse('{{ filters | json_encode | raw }}');
Stanley85
  • 389
  • 1
  • 5
  • 7
  • I had to use backtick (`) instead of single quotes in the function param because one of the JSON values had a single-quote in it (apostrophe essentially). – SteveExdia Apr 26 '23 at 16:09
14

You may use json_encode twig filter to pass your arrays into javascript:

Twig

{% set packages = [1, 2, 3, 4] %}

<script>
    var packages = {{ packages|json_encode }}
</script>

Output

<script>
    var packages = [1,2,3,4]
</script>
Dharman
  • 30,962
  • 25
  • 85
  • 135
Peyman Mohamadpour
  • 17,954
  • 24
  • 89
  • 100
1

Try this:

//javascript
const myArray = JSON.parse('{{ packages[0] }}');

Or this:

//javascript
const myArray = {{ packages[0] }};
Yega
  • 356
  • 5
  • 10
0

The existing answers didn't work for me. Specifically, it failed when the original array contained any string containing newlines (\n).

This is what worked for me:

let jsArray = JSON.parse('{{ twig_array|json_encode|e("js") }}');
goulashsoup
  • 2,639
  • 2
  • 34
  • 60
Magnus
  • 17,157
  • 19
  • 104
  • 189