【问题标题】:How can I check multiple if conditions in twig?如何检查树枝中的多个 if 条件?
【发布时间】:2019-03-22 19:27:29
【问题描述】:

如何检查 twig 中的多个 if 条件? 这些似乎都不起作用 而且它们看起来都很凌乱和沉重。

  {% if pageClass != "page-home" %}
  {% if bodyClass != "500" %}
  {% if bodyClass != "404" %}
         {% include '_components/type-bg' with {
                    content: {
                        slug: entry.slug|split(' ')|slice(0, 1)|join
                    },
                } only %}
   {% endif %}
   {% endif %}
   {% endif %}

我也试过下面的

    {% if (pageClass != "page-home") or (if bodyClass != "500") or (if bodyClass != "404")%}

      {% include '_components/type-bg' with {
                    content: {
                        slug: entry.slug|split(' ')|slice(0, 1)|join
                    },
                } only %}

    {% endif %}

【问题讨论】:

  • @LeKhan9 不。我上面的示例表明我已经尝试过该解决方案,但它不起作用
  • @Jessica 不应该是and 而不是or
  • @Iwan-Wijaya 我想检查这些条件是否为真。如果其中任何一个为真,则将此模板包含在内容中。一个页面不能是 500 404 和 page-home :-/
  • 哦,我没有看值,我认为你的第一个代码中的逻辑是正确的。我认为应该是{% if pageClass != "page-home" or bodyClass != "500" or bodyClass != "404 %} ?

标签: symfony twig octobercms craftcms


【解决方案1】:

您需要使用and 作为您的all condition need to satisfyexecute that code,所以它必须是and

{% if pageClass != "page-home" and bodyClass != "500" and bodyClass != "404" %} 
     {% include '_components/type-bg' with {
         content: {
             slug: entry.slug|split(' ')|slice(0, 1)|join
         },
     } only %}   
{% endif %}

更好的解决方案将来自 code block 只需使用 PHP 代码 [你可以在这里做所有 PHP 的事情] 使用 switch case or etc .. 来实现这一点,并且只传递 flag 之类的needToInclude 作为 boolean 来查看和使用它。

{% if needToInclude %} 
     {% include '_components/type-bg' with {
         content: {
             slug: entry.slug|split(' ')|slice(0, 1)|join
         },
     } only %}   
{% endif %}

如有疑问请留言

【讨论】:

  • 我猜仍然需要更多的咖啡 - 无论如何 +1 以在 PHP 方面进行操作。如果我多次需要此检查,我个人会向twig 添加一个自定义函数
  • 是的,但根据用户/她的经验,我想code block php code 可以帮助她,添加自定义功能会让用户不知所措:),但是是的,我同意多次使用 function 很重要更有意义。
【解决方案2】:

正确的检查如下

{% if pageClass != 'page-home' and bodyClass not in [ 500, 404, ] %}

意思是当pageClass不是主页时执行,并确保bodyClass不是错误状态

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-26
    相关资源
    最近更新 更多