0

I have some data that I need to retrieve from the Twig PHP template engine and convert into a JS JSON Array.

I am able to loop through the PHP array in TWIG and push the values to JS like so:

  var results = []
  {% for res in pqRes|reverse %}
        var res =  "{" + "{{res|raw}}" + "}"
        results.push(res)
  {% endfor %}

This creates an array like below when I console.log results

 0: "{value: 1, meta: 'Meets'}"
 1: "{value: 2, meta: 'Exceeds'}"
 2: "{value: 1, meta: 'Meets'}"
 3: "{value: 1, meta: 'Meets'}"
 4: "{value: 0, meta: 'Fails'}"

How can I push these values into a JSON array so that each item doesn't have the quotes around it?

Ultimately what I need to do is push the values into a data structure that looks like this:

var chart = new Chartist.Line('.ct-chart', {
 labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'],
 series: [{
  name: 'Workload',
  meta: {customData: 123},
  data: [
      {value: 1, meta: 'This can be anything and will be serialized'},
      {value: 4, meta: {text: 'Can even be Objects'}},
      {value: 2, meta: 10000},
      {value: 1, meta: 'This can be anything and will be serialized'},
      {value: 2, meta: 'This can be anything and will be serialized'}
 ]
 }]
}
});

Source (https://jsbin.com/kivole/1/edit?js,output)

Nick
  • 13
  • 1
  • 3
  • 8
    Use `json_encode()`. Don't build the json yourself. – Taplar Nov 20 '18 at 15:28
  • 1
    Possible duplicate of [Preferred method to store PHP arrays (json\_encode vs serialize)](https://stackoverflow.com/questions/804045/preferred-method-to-store-php-arrays-json-encode-vs-serialize) – Tom Nov 20 '18 at 15:29
  • Possible duplicate of [Use Javascript to access a variable passed through Twig](https://stackoverflow.com/questions/13928729/use-javascript-to-access-a-variable-passed-through-twig) – DarkBee Nov 20 '18 at 15:30
  • Yeah 100% just create a PHP array, then pass it through json_encode... the result is a JSON encoded string as you require. – Adam Nov 20 '18 at 15:30
  • The issue is that I have values being calculated on the TWIG page and after they are calculated they are pushed to the TWIG array like so {% if pqFailed == true %} {% set pqRes = pqRes | merge(["{value: 0, meta: 'failed'}"]) %} I have tried using {{pqRes|json_encode}} and still see the double quotes around each item in the array in the JS – Nick Nov 20 '18 at 15:36

1 Answers1

0

Your just pushings strings into a javascript array at this point. Don't use an array...

var obj = { {% for string in foo %}{{ string | raw }},{% endfor %} };

demo

DarkBee
  • 16,592
  • 6
  • 46
  • 58