如何在Timber的页脚中显示3条最近的帖子?

问题描述

所以,我现在为此动了两天。如何使用Timber和Twig在页脚中显示3条最近的帖子?我正在使用Timber的入门主题。 我在footer.PHP文件中执行的操作:

$timberContext = $GLOBALS['timberContext'];
if ( ! isset( $timberContext ) ) {
throw new \Exception( 'Timber context not set in footer.' );
}
$args = array(
'posts_per_page' => 3,);
$timberContext['featured'] = new Timber\PostQuery($args);
$templates = array( 'page-plugin.twig');
$timberContext['content'] = ob_get_contents();
ob_end_clean();
Timber::render( $templates,$timberContext );

在footer.twig中,我尝试显示它们:

<ul class = "featured-posts-list">
    {% for post in featured %}
        <li><a href="{{ post.link }}">{{ post.title }}</a></li>
    {% endfor %}
</ul>

现在的问题是它什么也不显示。如果我用footer.twig中的帖子替换featured,它将显示当前页面上的所有帖子。在我看来,Timber不处理我的帖子查询,我也不知道为什么。我一直在寻找答案,但没有找到答案。另外,这是我在这里的第一篇文章,因此,如果造成混淆,我在此先感到抱歉。

解决方法

所以,我刚刚找到了自己的问题的答案:)如果有人遇到类似的问题,我通过将变量添加到functions.php中的上下文中来解决它:

public function add_to_context( $context ) {
        //...previous variables...
        //the one I have added
        $context['featured'] = new Timber\PostQuery(array(
            'post_type' => 'post','posts_per_page' => 3,));
        return $context;
    }

然后在我的footer.twig内部,我像这样使用它:

<ul class = "featured-posts-list">
    {% for post in featured %}
        <li><a href="{{ post.link }}">{{ post.title }}</a></li>
    {% endfor %}
</ul>