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

Iterating through a 2 dimensional array in a template


Reply

3 Posts   1019 Views

Avatar
gwhizzl

20 September 2012 at 5:11am (Last edited: 20 September 2012 5:11am), Community Member, 3 Posts

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 %>
---$Title
---$Image
---<hr>
<% 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...

Avatar
martimiz

20 September 2012 at 10:49pm Forum Moderator, 1091 Posts

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')

Avatar
Willr

22 September 2012 at 5:06pm Forum Moderator, 5511 Posts

To clarify martimiz, your code must pass the template an instance of a ViewableData object (http://api.silverstripe.org/3.0/framework/view/ViewableData.html). 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 http://open.silverstripe.org/ticket/7892)