12

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?

2
  • 1
    can u elaborate more... Your question is not clear Commented Oct 19, 2018 at 8:46
  • thanx @DarkBee it is working Commented Oct 19, 2018 at 9:03

4 Answers 4

31

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

const filters = JSON.parse('{{ filters | json_encode | raw }}');
Sign up to request clarification or add additional context in comments.

1 Comment

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).
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>

1 Comment

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

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") }}');

Comments

1

Try this:

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

Or this:

//javascript
const myArray = {{ packages[0] }};

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.