【问题标题】:Liquid: How to combine two "UNLESS" conditions?液体:如何结合两个“除非”条件?
【发布时间】:2021-10-12 00:26:30
【问题描述】:

我在 Shopify 液体中工作,我正在寻找一种清晰且简单的方法来运行代码(在本例中初始化 jquery),仅当两个条件不成立时。

  1. 模板不是购物车
  2. 该模板不是具有多个产品变体的产品模板。

在这些情况下,我之前已经使用更简单的 IF 条件初始化了 JQuery。所以现在我想避免在这些情况下再次初始化 JQuery。

我可以用这个吗:

{% unless template contains 'cart' or template contains 'product' and product.variants.size > 1 %}
  {{ 'jquery-2.2.3.min.js' | asset_url | script_tag }}
{% endunless %}

“and”指的是“产品”模板是否清楚?所以喜欢If X != true OR (Y != true AND Z = true)

否则,我是否需要使用以下内容来确保 JQuery 不会被初始化两次?

{% unless template contains 'cart' %}
    {% unless template contains 'product' and product.variants.size > 1 %}
        {{ 'jquery-2.2.3.min.js' | asset_url | script_tag }}
    {% endunless %}
{% endunless %}
{% unless template contains 'product' and product.variants.size > 1 %}
    {% unless template contains 'cart' %}
        {{ 'jquery-2.2.3.min.js' | asset_url | script_tag }}
    {% endunless %}
{% endunless %}

【问题讨论】:

    标签: jquery shopify liquid


    【解决方案1】:

    您的解决方案

    首先,您使用嵌套代码提出的第二种替代方案将以两种形式工作:

    1. 使用购物车检查外部和内部产品
    2. 使用产品检查外部和内部购物车

    一般机制

    Shopify Liquid 在 {% if %}{% unless %} 语句中从右到左评估 andor 等运算符,例如,如果您有:

    <div>
    
      {% unless false or false and true %}
        {{"The evaluated condition is false"}}
      {% else %}
        {{"The evaluated condition is true"}}
      {% endunless %}
    
    </div>

    这将输出{{"The evaluated condition is false"}},因为:

    1. false 和 true 评估为 false
    2. false 或 false 评估为 false
    3. {% unless false %} 输出 {{"The evaluated condition is false"}}

    我认为单个 {% unless %} 语句更简洁,并且可以避免嵌套,但您可以使用任何一种解决方案。

    【讨论】:

    • 因为您不能在 Liquid if/unless 比较中使用括号,为避免混淆,我通常建议使用 assign 存储要比较的变量子集(AND 或 OR,取决于在这种情况下什么是有意义的)然后运行我的 if/unless 仅使用 AND 或 OR,从不同时使用两者。对于这个问题,我可能会使用{% if template contains 'product' and product.variants.size &gt; 1 %}{% assign product_has_variants = true %}{% endif %}{% unless unless template contains 'cart' or product_has_variants %}&lt;stuff&gt;{% endunless%}
    猜你喜欢
    • 2019-04-05
    • 2021-09-21
    • 2022-10-23
    • 2012-10-17
    • 1970-01-01
    • 2013-01-18
    • 1970-01-01
    • 1970-01-01
    • 2021-12-25
    相关资源
    最近更新 更多