【发布时间】:2015-10-24 09:44:16
【问题描述】:
我的目标是使用 Twig 代码仅在我的 wordpress 的索引页面上简单地输出一些内容。我设置了一个名为 Home 的静态页面。
我已经在我的 base.twig 中尝试过这个:
{% if is_front_page %}
Homepage content
{% endif %}
但这并没有做任何事情,我只是发现由于某种原因不容易找到它。
感谢任何帮助!提前致谢
【问题讨论】:
我的目标是使用 Twig 代码仅在我的 wordpress 的索引页面上简单地输出一些内容。我设置了一个名为 Home 的静态页面。
我已经在我的 base.twig 中尝试过这个:
{% if is_front_page %}
Homepage content
{% endif %}
但这并没有做任何事情,我只是发现由于某种原因不容易找到它。
感谢任何帮助!提前致谢
【问题讨论】:
Timber comes with the fn(也有 function 的别名)让您执行外部 PHP 函数。所以这样的事情会起作用:
{% if fn('is_front_page') %}
Homepage content
{% endif %}
【讨论】:
我喜欢在我的树枝模板之外保留特殊功能。在 Timber 中,您可以定义自己的上下文,您可以在其中设置自己的变量。
创建一个名为front-page.php 的文件并添加:
<?php
$context = Timber::get_context();
// Set a home page variable
$context['is_front_page'] = 'true';
Timber::render(array('home.twig'), $context);
然后你可以使用is_front_page 作为你想要的变量:
{% if is_front_page %}
Homepage content
{% endif %}
【讨论】:
您可以通过扩展 wood_context 过滤器来创建全局内容。
将以下内容添加到您的functions.php文件中,它将使用调用Timber::get_context();添加到所有模板中。
add_filter('timber_context', 'add_to_context');
function add_to_context($context){
/* Add to Timber's global context */
$context['is_front_page'] = is_front_page();
return $context;
}
【讨论】: