如何在 twig Timber 代码中编写 wordpress 函数 "is_front_page()"?
How do I write the wordpress function "is_front_page()" in twig Timber code?
我的目标是使用 Twig 代码仅在我的 wordpress 的索引页上输出一些内容。我已经设置了一个名为主页的静态页面。
我已经在我的 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 %}
您可以通过扩展 timber_context fitler 创建全局内容。
将以下内容添加到您的 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;
}
我的目标是使用 Twig 代码仅在我的 wordpress 的索引页上输出一些内容。我已经设置了一个名为主页的静态页面。
我已经在我的 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 %}
您可以通过扩展 timber_context fitler 创建全局内容。
将以下内容添加到您的 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;
}