【问题标题】:How do I write the wordpress function "is_front_page()" in twig Timber code?如何在 twig Timber 代码中编写 wordpress 函数“is_front_page()”?
【发布时间】:2015-10-24 09:44:16
【问题描述】:

我的目标是使用 Twig 代码仅在我的 wordpress 的索引页面上简单地输出一些内容。我设置了一个名为 Home 的静态页面。

我已经在我的 base.twig 中尝试过这个:

{% if is_front_page %}
 Homepage content
{% endif %}

但这并没有做任何事情,我只是发现由于某种原因不容易找到它。

感谢任何帮助!提前致谢

【问题讨论】:

    标签: php wordpress twig


    【解决方案1】:

    Timber comes with the fn(也有 function 的别名)让您执行外部 PHP 函数。所以这样的事情会起作用:

    {% if fn('is_front_page') %}
      Homepage content
    {% endif %}
    

    【讨论】:

    • 很好,我已经找到了解决方案,但这是另一种方法!感谢您让我知道这个功能!
    【解决方案2】:

    我喜欢在我的树枝模板之外保留特殊功能。在 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 %}
    

    【讨论】:

    • 这在我仔细考虑之后几乎太明显了......这可能是它运作良好的原因。
    【解决方案3】:

    您可以通过扩展 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;
    }
    

    【讨论】:

    • 这应该是最佳实践和可维护代码的首选方式
    猜你喜欢
    • 2018-03-17
    • 1970-01-01
    • 2016-10-08
    • 1970-01-01
    • 2019-01-09
    • 1970-01-01
    • 2020-08-31
    • 1970-01-01
    • 2020-06-16
    相关资源
    最近更新 更多