Skip to main content

This site requires you to update your browser. Your browsing experience maybe affected by not having the most up to date version.

Template Questions /

Moderators: martimiz, Sean, Ed, biapar, Willr, Ingo, swaiba

Iterating through a 2 dimensional array in a template

Go to End

3 Posts   1868 Views


Community Member, 3 Posts

20 September 2012 at 5:11am

Edited: 20/09/2012 5:11am

So I'm using a custom function in a page controller to get some data objects, and then display them in the template. Sounds simple, but I can't get it to work.

Here is my function in the page controller:

function getProducts() {
---$Products = array();
---$ProductIDs = array('10,'22','50');
---foreach ($ProductIDs as $key => $value) {
------$Products[$key] = $this->getProductByID($value);
---return $Products;

And in the template...

<% control getProducts %>
<% end_control %>

But no data appears. However, if I put "return $Products[0]" in the function, it successfully returns a Product object and displays the $Title etc...


Forum Moderator, 1203 Posts

20 September 2012 at 10:49pm

The template engine expects the object passed to a control function to be either a DataObject or a DataObjectsSet, so in this case your function should preferrably return a 'DataObjectSet of DataObjectSets' (this is for version 2.4.x, v3 uses DataLists).

There are some usefull solutions in other posts on these forums (for instance: google 'silverstripe template array')


Forum Moderator, 5521 Posts

22 September 2012 at 5:06pm

To clarify martimiz, your code must pass the template an instance of a ViewableData object ( This includes DataObjects or ArrayData objects. ArrayData is simply a wrapper around an array.

For 3.0 your function would look like

function getProducts() { 
$products = array();

foreach (array('10,'22','50') as $id) 
$products[] = $this->getProductByID($value); 
return new ArrayList($products); 

<% control $Products %>
<% end_control %>

(this should probably be documented so created