1

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.

Masha
  • 827
  • 1
  • 10
  • 30
  • Your code should [work](http://twigfiddle.com/q5rn0o) as is (except for the double `|` before the json_encode), be sure you pass the correct data to the template. – DarkBee Oct 26 '16 at 16:34
  • See the answer here for a way to deal with variable numbers of arguments to a JS function: http://stackoverflow.com/questions/2141520/javascript-variable-number-of-arguments-to-function – duncan Oct 27 '16 at 08:04

1 Answers1

1

Twig

<script>
{% for var, value in parms %}
    var {{ var }} = {{ value|json_encode|raw }};
{% endfor %}
   console.log({{ parms|keys|join(',') }});
</script>

Input JSON

{"parms":{"arr1":{"foo":"bar","bar":"foo"},"arr2":{"foo":"bar","bar":"foo"},"arr3":{"foo":"bar","bar":"foo"}}}

Output

var arr1 = {"foo":"bar","bar":"foo"};
var arr2 = {"foo":"bar","bar":"foo"};
var arr3 = {"foo":"bar","bar":"foo"};
console.log(arr1,arr2,arr3);

fiddle

DarkBee
  • 16,592
  • 6
  • 46
  • 58