1

在 Silverstripe 4 中,我想在单个页面模板上使用两个循环。这些数组是在我的页面控制器内的单个函数内创建的。

我的想法是创建两个 ArrayList,然后将它们组合成第三个 ArrayList,然后将其传递给模板。

使用 SQLSelect,我有一些代码可以创建数据的 ArrayList。$queryArray 是一个 key=>value 对的数组。

$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 似乎拥有所有数据,但我无法弄清楚如何正确访问模板中的数据。

这甚至可能吗?如果是这样,我做错了什么?

4

1 回答 1

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. 
于 2018-05-24T12:46:51.247 回答