Silverstripe - Looping over non-associative array in template

danbroooks picture danbroooks · Jul 29, 2013 · Viewed 7.7k times · Source

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"?

Answer

Zauberfisch picture Zauberfisch · Jul 29, 2013

as far as I know this is not possible, you need to wrap each item into a ArrayData object

public function ArrayList()
{
    $ArrayList = ArrayList::create(array(
        ArrayData::create(array('Text' => 'this')),
        ArrayData::create(array('Text' => 'is')),
        ArrayData::create(array('Text' => 'a')),
        ArrayData::create(array('Text' => 'test')),
    ));
    return $ArrayList;
}

and the template:

<% loop $ArrayList %>$Text<% end_loop %>

// NOTE: ___::create() is the new ___() on steroids