在SilverStripe上按类别过滤的循环博客文章


Loop blog post filtered by a category on SilverStripe

我正在一个SilverStripe网站上工作,并且已经安装了博客模块。

我的博客设置了多个类别,如新闻事件公告照片库等。

我遇到的问题是,我想在首页上展示每个类别的最新博客文章(标题、图片、一些内容)。

使用此解决方案,我可以轻松地循环博客文章:http://www.silverstripe.org/community/forums/blog-module-forum/show/102585?start=8

/mysite/code/Page.php

class Page_Controller extends ContentController {
    public function latestBlog($num = 3) {
        return BlogPost::get()
                ->sort('PublishDate', 'desc')
                ->limit($num);
    }
}

/themes/ssimple/templates/Page.ss

<ol>
<% loop $latestBlog %>
    <li>$Title</li>
    <p>$Content</p>
<% end_loop %>
</ol>

但我不知道如何在按类别过滤时循环。例如,类似这样的逻辑:

return BlogPost::get()
        ->FILTER('Category', 'News')
        ->sort('PublishDate', 'desc')
        ->limit($num);

这个想法是循环新闻并以某种方式对其进行编码,使其在头版上看起来不同,然后循环Photo Galleries

我找不到任何关于如何做到这一点的有效方法。

这样做可能吗?

您想在DataList上使用relation方法:http://api.silverstripe.org/3.3/class-DataList.html#_relation

return BlogCategory::get()
    ->filter('Title', 'News')
    ->relation('BlogPosts')
    ->sort('PublishDate', 'DESC')
    ->limit($num);

这将返回一个按定义的类别(新闻)筛选的博客文章列表。