SilverStripe 4 (cms4 / SS4):如何制作同级页面的下一个/上一个导航?

SilverStripe 4 (cms4 / SS4): How to make Next / Previous navigation of sibling pages?

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

$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/

嗯,是的,您拥有的代码正是您获得下一页 link 所需的代码。
让我分解一下:

$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 是您正在查看的当前页面。
假设你有一个标准的页面渲染设置,你可以按以下方式使用它:

(尽管如此,我做了 1 个小修改。在下面的示例中,我没有在 php 中调用 ->Link(),而是在模板中调用它。相反,我 return 完整的 $nextPageAfterTheCurrentPage 到模板,这允许我在需要时也可以在模板中使用 $Title)

<?php
// in your app/srv/Page.php

namespace \;

use SilverStripe\CMS\Model\SiteTree;

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

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