【问题标题】:Liquid: How to assign the output of an operator to a variable?Liquid:如何将运算符的输出分配给变量?
【发布时间】:2020-05-10 05:59:48
【问题描述】:

我正在为 Shopify 使用 Liquid 模板。我希望仅当月份恰好是 12 月时才显示一些元素。由于有多个元素需要这个,我想在文档顶部设置一个变量,以便稍后参考。这就是我的工作:

<!-- At the top of the page -->
{% assign month = 'now' | date: "%m" %}
{% if month == "12" %}
{% assign isDecember = true %}
{% else %}
{% assign isDecember = false %}
{% endif %}

<!-- Only show in December -->
{% if isDecember %}
Happy Holidays
{% endif %}

这可行(为了测试我将“12”更改为当前月份),但它非常难看。在大多数语言中,我会这样做:

{% assign isDecember = (month == "12") %}

Liquid 不接受括号,所以显然这行不通。没有括号它也不起作用。文档中有 using operatorsassigning static values to variables 的示例,但没有关于将两者结合起来的内容。

我可以将| 过滤器的输出分配给一个变量,但似乎没有过滤器可以覆盖每个运算符(甚至是必要的“==”),所以这并不令人满意。

有没有办法将运算符的输出分配给 Liquid 中的变量?

【问题讨论】:

    标签: operators variable-assignment liquid assign assignment-operator


    【解决方案1】:

    您可以完全避免使用中间布尔标志变量isDecember 作为液体assign,只有布尔变量似乎在if/endif 中不起作用。以下是解决方案。

    1. 只需使用纯字符串:
    {% assign month = 'now' | date: "%m" %}
    
    {% if month == "12" %}
      Happy Holidays
    {% endif %}
    
    1. 或者在ifs 中使用纯字符串赋值(不是布尔值赋值):
    {% if month == "12" %}
      {% assign phrase = "Happy Holidays" %}
    {% else %}
      {% assign phrase = "Happy usual time of the year" %}
    {% endif %}
    
    Now my message to you is: {{ phrase }}
    
    1. 还想取消中介isDecember?如果您在 if/else 的任一子句中放置一些虚拟文本分配,那也可以。
    {% if month == "12" %}
      {% assign dummy = "summy" %}
      {% assign isDecember = true %}
    {% else %}
      {% assign isDecember = false %}
    {% endif %}
    
    

    希望对您有所帮助。

    【讨论】:

      【解决方案2】:

      没有办法优雅地做到这一点,根据this,它们不支持三元运算符。有人提到有人在尝试类似的事情。

      稍短/不同的版本是:

      {% assign month = 'now' | date: "%m" %}
      {% liquid
      case month
      when '12'
        assign isDecember = true
      else
        assign isDecember = false
      endcase %}
      

      【讨论】:

        猜你喜欢
        • 2017-01-11
        • 2014-12-06
        • 1970-01-01
        • 2021-08-05
        • 2020-01-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多