亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用 Timber 在頁腳中顯示 3 個最近的帖子?

如何使用 Timber 在頁腳中顯示 3 個最近的帖子?

PHP
烙印99 2023-10-15 14:39:46
所以,我已經為此絞盡腦汁兩天了。如何使用 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 不處理我的帖子查詢,我不知道為什么會這樣。我一直在尋找答案,但沒有找到。另外,這是我在這里發表的第一篇文章,所以如果令人困惑,我提前表示歉意。
查看完整描述

1 回答

?
天涯盡頭無女友

TA貢獻1831條經驗 獲得超9個贊

所以,我剛剛找到了我自己問題的答案:)如果有人遇到類似的問題,我通過將變量添加到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>


查看完整回答
反對 回復 2023-10-15
  • 1 回答
  • 0 關注
  • 117 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號