所以,我已經為此絞盡腦汁兩天了。如何使用 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>
- 1 回答
- 0 關注
- 117 瀏覽
添加回答
舉報
0/150
提交
取消