Ad

How To Convert A Twig Array Into JavaScript Array

- 1 answer

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?

Ad

Answer

Ehsan jan, salam!

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>
Ad
source: stackoverflow.com
Ad