Silverstripe - Looping over non-associative array in template

那年仲夏 提交于 2019-12-08 16:14:03

问题


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


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/17921642/silverstripe-looping-over-non-associative-array-in-template

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!