1

I am trying to get an array produced in my php controller to pass data to javascript in a .twig file.

I am able to access all the values in a for loop in the .twig but when trying to get the value in javascript, I am only able to get the whole array by using:

var markers = {{ products|json_encode|raw }};

This produces:

var markers = [{"id":"1","name":"x","location":"San Diego"},{"id":"2","name":"y","location":"LA"}];

When trying to access specific values using a for loop within the javascript:

for (i = 0; i < markers.length; i++) 
{ 
alert(markers[i][0])
} 

Using console.log / alert I get [undefined] for markers[i][0] and [object object] if I loop through markers[i]. The length is correct.

This is my first project using .twig so I don't know if I am just missing something really obvious as I can't seem to find my problem.

Any help would be appreciated!

2
  • In twig use a data attribute on an element, use a filter to escape any single quotes and then use JSON.parse in Javascript to get the data. There is a good tutorial post here: cruftlesscraft.com/… Commented Jul 29, 2019 at 16:04
  • Still can't seem to pull any data from the array, only getting "", is it not possible to take the values from var markers = {{ products|json_encode|raw }}; ?. From the example given console.log($entryInfoObjects); shows me the array in console 0: {location: "SD", name: "x"} 1: {location: "LA", name: "y"} but the example given var entryInfo = { location: '{{ product.location }}',}; for extracting specific data gives me " "... Commented Jul 29, 2019 at 17:22

1 Answer 1

1

It appears that your issue lies in the javascript for loop.

Look here:

var markers = [{"id":"1","name":"x","location":"San Diego"},{"id":"2","name":"y","location":"LA"}];

None of the objects within your array have a property named 0. You only have properties called id, name and location.

Change your loop to something like:

for (i = 0; i < markers.length; i++) 
{ 
  alert(markers[i]['name'])
} 

You should see it shows you the value of each objects name property.

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

Comments

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.