silverstripe 3博客下一篇和上一篇文章

时间:2016-11-08 03:18:13

标签: php silverstripe

我正在尝试从我正在查看的BlogPost中返回下一个(较新的)和之前的(较旧的)BlogPost。

我已将其设置为扩展程序:

<?php
class BlogPost_Extension extends DataExtension {

public function getBlogSibling($Mode = 'next') {
    if($Mode == 'next'){
        $pages = BlogPost::get()->filter(array(
        'ParentID' => $this->owner->ParentID,
        'PublishDate:GreaterThan' => $this->owner->PublishDate
        ))->Sort('PublishDate ASC')->limit(1);
    } elseif($Mode == 'prev'){
        $pages = BlogPost::get()->filter(array(
        'ParentID' => $this->owner->ParentID,
        'PublishDate:LessThan' => $this->owner->PublishDate
        ))->Sort('PublishDate DESC')->limit(1);
    }

    if ($pages->count()) {
        return $pages->First();
    }
    return false;
}

}

并在模板中使用它:

<% if $BlogSibling('next') %><a href="$BlogSibling('next').Link">newer story</a><% end_if %>
<% if $BlogSibling('prev') %><a href="$BlogSibling('prev').Link">older story</a><% end_if %>

但是两者都返回相同的结果,下一个(更新的)BlogPost - 我确定它有点愚蠢,我忽略了......!)

(silverstripe 3.1.4 / blog module~2.4)

1 个答案:

答案 0 :(得分:1)

Another (better) solution, found by munomono

您需要扩展BlogPost_Controller而不是BlogPost。比添加以下功能

  public function PrevBlogPost() {
    $sort = $this->owner->Sort;
    $prevSort = $sort - 1;

    if($prev = $this->owner->Parent()->getBlogPosts()->find('Sort', $prevSort)) {
      return $prev;
    }
  }

  public function NextBlogPost() {
    $sort = $this->owner->Sort;
    $nextSort = $sort + 1;

    if($next = $this->owner->Parent()->getBlogPosts()->find('Sort', $nextSort)) {
      return $next;
    }
  }

在您的模板中

  <% if $PrevBlogPost %>
    <a href="$PrevBlogPost.Link" title="$PrevBlogPost.Title">
      <i class="fa fa-angle-left"></i>vorheriger Beitrag
    </a>
  <% end_if %>
  <% if $NextBlogPost %>
    <a href="$NextBlogPost.Link" title="$NextBlogPost.Title">
      nächster Beitrag<i class="fa fa-angle-right"></i>
    </a>
  <% end_if %>

当然,您可以将这些功能合并为一个。