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?
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?
I have an array from twig named filters, this single line did the job
const filters = JSON.parse('{{ filters | json_encode | raw }}');
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>
Try this:
//javascript
const myArray = JSON.parse('{{ packages[0] }}');
Or this:
//javascript
const myArray = {{ packages[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") }}');