How to convert a Twig array into JavaScript array

11,012

Solution 1

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>

Solution 2

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

const filters = JSON.parse('{{ filters | json_encode | raw }}');

Solution 3

Try this:

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

Or this:

//javascript
const myArray = {{ packages[0] }};
Share:
11,012

Related videos on Youtube

ehsan
Author by

ehsan

Updated on June 04, 2022

Comments

  • ehsan
    ehsan almost 2 years

    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?

  • Arleigh Hix
    Arleigh Hix over 2 years
    This does not work with Twig v2.13.1, use @Stanley85 's answer stackoverflow.com/a/63391632/6127393