SilverStripe 4cms4 / SS4:如何进行同级页面的下一个/上一个导航?

问题描述

我希望在同级页面上创建一个简单的“下一个”和“上一个”导航,以允许用户单击它们。它们都在单个级别上。我找到了一些文档和一个加载项(下面的链接),但是这些文件旨在显示没有页面的数据列表。 我似乎找不到任何有关如何实现此目标的教程或信息。 我被告知以下起点,但不确定如何完成:

$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是您正在查看的当前页面。
假设您具有呈现页面的标准设置,则可以通过以下方式使用它:

(尽管,我做了1个小的修改。在下面的示例中,我没有在php中调用-> Link(),而是在模板中对其进行了调用。相反,我将完整的$ 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而不是当前Sort之外,您还必须搜索/过滤LessThan。