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)

5
  • 8
    Use json_encode(<your array>). Don't build the json yourself. Commented Nov 20, 2018 at 15:28
  • 1
    Possible duplicate of Preferred method to store PHP arrays (json_encode vs serialize) Commented Nov 20, 2018 at 15:29
  • Possible duplicate of Use Javascript to access a variable passed through Twig Commented Nov 20, 2018 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. Commented Nov 20, 2018 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 Commented Nov 20, 2018 at 15:36

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

This worked perfect! I was overthinking this. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.