phpsilverstripe

Silverstripe - Looping over non-associative array in template


How can this be done inside of a template? I have done it with ArrayData using the key in the template loop to access values from the template, but if I have an arbitrary array of strings with no keys, what variable do I use to access the values?

If in my controller I have this:

public function ArrayList()
{
    $ArrayList = new ArrayList(array('this', 'is', 'a', 'test'));
    return $ArrayList;
}

And this in my template:

<% loop $ArrayList %>1<% end_loop %>

What do I put in place of 1 to get the template to spit out "this is a test"?


Solution

  • Rather than creating a new ArrayData instance each time, you can just use $Me. So you would have:

    public function ArrayList()
    {
        $ArrayList = new ArrayList(array('this', 'is', 'a', 'test'));
        return $ArrayList;
    }
    

    And, in your template:

    <% loop $ArrayList %>$Me<% end_loop %>
    

    $Me refers to the current item in the loop. In this case, it'll be the strings in the array.