-1

I created a twig array and populated it with objects, and i want to parse that to an javascript array and objects

Twig array:

itm = array:1 [
  0 => array:2 [
    "Test1" => "Testtt1"
    "Test2" => "Testtt2"
  ]
]

I tried to parse it like this but it return and empty array:

var arrAll = [];
 arrAll = {{ itm|json_encode }} 
6
  • 1
    Your question is not clear. Do you have the array available in js script from php ? Commented Sep 9, 2020 at 9:46
  • 1
    Does this answer your question? variable Twig in Javascript Commented Sep 9, 2020 at 9:53
  • @MrKhan I need to parse that twig array to a javascript but with json_encode() it doesnt work, when i console.log that javascript array it returns me an empty array Commented Sep 9, 2020 at 12:29
  • 1
    Are you sure you posted a correct dump of the array? I think it cannot be array:8 with only two elements (it should be array:2) Commented Sep 9, 2020 at 12:31
  • @MarcosLabad Yes there were 8 elements in the array but i deleted them for shorter explanation. Commented Sep 9, 2020 at 12:34

1 Answer 1

0

You have to get the raw variable, otherwise it will fail:

 var arrAll = [];
 arrAll = {{ itm|json_encode|raw }} 
Sign up to request clarification or add additional context in comments.

4 Comments

I tried this but it still is returning an empty array
I can reproduce your array by declaring it this way: $itm = [ [ 'Test1' => 'Testtt1', 'Test2' => 'Testtt2' ] ]; Can you try it? I made the test and it worked perfectly well.
OP's example array does not reflect his/her live data though
@MarcosLabad yes when i make an array and fill it, it does get the value. But I am getting this twig array value from a hook. Eitherway when i dump the twig array it does return the array , but nothing in js.

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.