简体   繁体   English

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

[英]How do I display 3 recent posts in footer with Timber?

So, I am beating my head over this for 2 days now.所以,我现在已经为此苦恼了 2 天。 How do I display 3 recent posts in footer using Timber and Twig?如何使用 Timber 和 Twig 在页脚中显示 3 个最近的帖子? I am using a starter theme from Timber.我正在使用 Timber 的入门主题。 What I did inside my footer.php file:我在 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 );

And inside my footer.twig I tried displaying them:在我的 footer.twig 我尝试显示它们:

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

Now the problem is it displays nothing.现在的问题是它什么也不显示。 If I replace featured with posts in footer.twig, it displays whatever posts are on the current page.如果我用 footer.twig 中的帖子替换特色,它会显示当前页面上的所有帖子。 It seems to me that Timber doesn't process my post query and I don't know why is that.在我看来,Timber 没有处理我的帖子查询,我不知道为什么会这样。 I was looking for an answer but didn't find one.我一直在寻找答案,但没有找到。 Also, this is my first post here, so I am sorry in advance if it is confusing.另外,这是我在这里的第一篇文章,所以如果令人困惑,我很抱歉。

So, I just found the answer to my own question:) In case someone has a similar problem, I resolved it by adding the variable to the context inside functions.php:所以,我刚刚找到了我自己的问题的答案:) 如果有人遇到类似的问题,我通过将变量添加到 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;
    }

Then inside my footer.twig I use it like this:然后在我的footer.twig里面我这样使用它:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM