Jump to:

3392 Posts in 976 Topics by 852 members

Template Questions

SilverStripe Forums » Template Questions » Iterating through a 2 dimensional array in a template

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

Page: 1
Go to End
Author Topic: 792 Views
  • gwhizzl
    Avatar
    Community Member
    3 Posts

    Iterating through a 2 dimensional array in a template Link to this post

    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...

  • martimiz
    Avatar
    Forum Moderator
    1035 Posts

    Re: Iterating through a 2 dimensional array in a template Link to this post

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

  • Willr
    Avatar
    Forum Moderator
    5462 Posts

    Re: Iterating through a 2 dimensional array in a template Link to this post

    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)

    792 Views
Page: 1
Go to Top

Want to know more about the company that brought you SilverStripe? Then check out SilverStripe.com

Comments on this website? Please give feedback.