Search code examples
operatorsvariable-assignmentliquidassignassignment-operator

Liquid: How to assign the output of an operator to a variable?


I'm working with Liquid templates for Shopify. I want some elements to show up only if the month happens to be December. Since there are multiple elements that need this, I want to set a variable at the top of the document and refer to it later. Here's what I've got that's working:

<!-- 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 %}

This works (for testing I change "12" to the current month) but it is pretty ugly. In most languages I would do something like this:

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

Liquid doesn't accept parentheses, so obviously this won't work. And it doesn't work without parentheses either. The documentation has examples for using operators and for assigning static values to variables, but nothing about combining the two.

I can assign the output of a | filter to a variable, but there don't seem to be filters to cover every operator (or even the necessary "=="), so that's unsatisfactory.

Is there any way to assign the output of an operator to a variable in Liquid?


Solution

  • There isn't a way to do that elegantly and according to this, they won't support ternary operators. There's a mention of someone trying a similar thing.

    A slightly shorter/different version would be:

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