3214 Posts in 848 Topics by 810 members
|
Page:
1
|
Go to End | |
| Author | Topic: | 345 Views |
-
Iterating through a 2 dimensional array in a template

20 September 2012 at 5:11am Last edited: 20 September 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 %>
---$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...
-
Re: Iterating through a 2 dimensional array in a template

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')
-
Re: Iterating through a 2 dimensional array in a template

22 September 2012 at 5:06pm
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)
| 345 Views | ||
|
Page:
1
|
Go to Top |


