I have got 2 arrays which I pass to twig. The first one is
array(1) {
[0]=>
array(2) {
["name"]=>
string(5) "name1"
["data"]=>
array(2) {
[0]=>
array(2) {
[0]=>
int(1474837200000)
[1]=>
int(1244)
}
[1]=>
array(2) {
[0]=>
int(1474923600000)
[1]=>
int(3100)
}
}
and the 2nd one
array(1) {
["positive"]=>
array(1) {
[0]=>
array(2) {
[0]=>
int(1474837200000)
[1]=>
int(371)
}
}
I pass these 2 arrays to my twig template and after that try to put their contents to the screen with JS
document.write({{array1|json_encode|raw}})
or document.write({{array2|json_encode|raw}})
The problem is while second array is printed OK, the first one is printed only [object Object]
without any contents further, if I try to access the keys of the first array with array1.0.name
(I want name1 here) I get blank screen.
{{dump(array1)}}
works ok in both cases
UPD Finally I got it working. The problem is that I need to access twig variable inside Javascript function. It gets only arrays, even just a plain string must be converted to array. If it gets associative array, the result is [object Object]. Is there a reason for such behaviour?
And the second question related to the problem. Is it possible to use Twig for-loop inside JS functions? Consider this JS code:
Myfunction([ [array1], [array2], [array3], [arrayN] ]);
Each time I get variable amount of arrays that I need to pass to JS. How can that be done? Should I try to make a JS array from twig one somehow or there is a more elegant solution? Thank you.