在Silverstripe 4中,我想在单页模板上使用两个循环。数组是在页面控制器内的单个函数内创建的。
我的想法是创建两个ArrayLists,然后将它们组合成第三个ArrayList,我将其传递给模板。
使用SQLSelect,我有一些代码可以创建数据的ArrayList。 $ queryArray是key =>值对的数组。
$sqlQuery = new SQLSelect();
$sqlQuery->setFrom('Wine');
$sqlQuery->addWhere($queryArray);
$results = $sqlQuery->execute();
$SSArrayList = new ArrayList; //new ArrayList;
foreach($results as $result) {
$SSArrayList->push(new ArrayData($result));
}
我还有一些其他代码可以从相同的$ results中创建另一个ArrayList:
foreach($results as $result) {
if (!empty($result['BrandName'])) {
$JSBrandsArray->push(array('Brandname'=>$result['BrandName']));
}
}
然后,第三个ArrayList组合了这两个数组:
$mainArray = new ArrayList;
$mainArray->push($SSArrayList);
$mainArray->push($JSBrandsArray);
$ mainArray传递给模板,如下所示:
return $this->customise(array('MainArray'=>$mainArray))->renderWith("Layout/WinesList");
然后,在WinesList.ss模板中,我想我可以这样做:
<% loop $MainArray %>
<% loop $SSArrayList %>
// show results from $SSArrayList
<% end_loop %>
<% loop $JSBrandsArray %>
// show results from $JSBrandsArray
<% end_loop %>
<% end_loop %>
如果我从页面控制器获取var_dump()$ mainArray,$ mainArray似乎拥有所有数据,但我无法弄清楚如何正确访问模板中的数据。
这甚至可能吗?如果是这样,我做错了什么?
答案 0 :(得分:0)
我意识到我不需要$ mainArray。可以使用renderWith方法将多个数组发送到模板。这是我到达的解决方案:
return $this->renderWith("Layout/WinesList",array(
'SS_WinesArray' => $SS_WinesArray,
'JS_CountriesArray' => $JS_CountriesArray,
'JS_BrandsArray' => $JS_BrandsArray,
// more arrays can be added here and looped in the template below
));
<% loop $SS_WinesArray %>
// I do JS stuff with this, which interacts with the categories
// I have set up in the other arrays, but prefixed it SS to
// differentiate it from the other arrays, which I'm using as category filters
<% end_loop %>
<% loop $JS_CountriesArray %>
// do JS stuff with the just the $JS_CountriesArray
<% end_loop %>
<% loop $JS_BrandsArray %>
// do JS stuff with the just the $JS_BrandsArray
<% end_loop %>
// loop through more arrays, if added to the renderWith method above.