SilverStripe 4(cms4/SS4):如何进行兄弟页面的下一个/上一个导航



我希望在同级页面上创建一个简单的Next和Previous导航,让用户可以点击它们。它们都在一个层面上。我发现了一些文档和一个插件(下面的链接(,但这些都是为了显示数据列表而不是页面。我似乎找不到任何关于如何实现这一目标的教程或信息。有人建议我从以下出发,但不确定如何完成:

$nextlink = SiteTree::get()->filter(['ParentID' => $this->ParentID, 'Sort:GreaterThan' => $this->Sort])->first()->Link();

https://github.com/fromholdio/silverstripe-paged

https://docs.silverstripe.org/en/4/developer_guides/search/searchcontext/

嗯,是的,你在那里的代码正是你获得下一页链接所需要的
让我分解一下:

$nextlink = SiteTree::get()->filter(['ParentID' => $this->ParentID, 'Sort:GreaterThan' => $this->Sort])->first()->Link();

是的单行版本

$allPages = SiteTree::get();
$allPagesOnTheSameLevel = $allPages->filter(['ParentID' => $this->ParentID]);
// SilverStripe uses the DB Field "Sort" to decide how to sort Pages. 
// Sort 0 is at the top/beginning, Sort 999... at the end. So if we want the next
// page, we just need to get the first page that has a higher "Sort" value than 
// the current page. Normally ->filter() would search for equal values, but if you 
// add the modifier `:GreaterThan` than it will search with >. And for PreviousPage 
// you can use :LessThan
$currentPageSortValue = $this->Sort;
$allPagesAfterTheCurrentPage = $allPagesOnTheSameLevel->filter(['Sort:GreaterThan' => $currentPageSortValue]);
$nextPageAfterTheCurrentPage = $allPagesAfterTheCurrentPage->first();
if ($nextPageAfterTheCurrentPage && $nextPageAfterTheCurrentPage->exists()) {
$nextlink = $nextPageAfterTheCurrentPage->Link();
}

这是PHP代码,它假设$this是您正在查看的当前页面
假设您有一个标准的页面渲染设置,您可以通过以下方式使用它:

(不过,我做了一个小修改。在下面的例子中,我没有在php中调用->Link((,而是在Template中调用它。相反,我将完整的$nextPageAfterTheCurrentPage返回到模板中,这允许我在模板中使用$Title(如果需要的话(

<?php
// in your app/srv/Page.php
namespace ;
use SilverStripeCMSModelSiteTree;
class Page extends SiteTree {
// other code here

// add this function:
public function NextPage() {
$allPages = SiteTree::get();
$allPagesAfterTheCurrentPage = $allPages->filter(['ParentID' => $this->ParentID, 'Sort:GreaterThan' => $this->Sort]);
$nextPageAfterTheCurrentPage = $allPagesAfterTheCurrentPage->first();
return $nextPageAfterTheCurrentPage;
}
// other code here
}

然后,在模板(可能是Page.ss(中,您可以执行:

<!-- other html here -->
<% if $NextPage %>
<!-- you can use any propery/method of a page here. $NextPage.ID, $NextPage.MenuTitle, ... -->
<!-- if you use something inside an html attribute like title="", then add .ATT at the end, this will remove other " characters to avoid invalid html -->
<a href="$NextPage.Link" title="$NextPage.Title.ATT">To the next Page</a>
<% end_if %>
<!-- other html here -->

对于上一页,只需再次执行相同的操作,但您必须搜索/筛选LessThan,而不是搜索/筛选当前排序的GraterThan。

最新更新