skip to Main Content

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?

2

Answers


  1. 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 %}
    
    Login or Signup to reply.
  2. You could altogether avoid using an intermediary boolean flag variable isDecember as Liquid assign with only boolean variables seems to not working within if/endif. Here are the solutions.

    1. Just use plain strings:
    {% assign month = 'now' | date: "%m" %}
    
    {% if month == "12" %}
      Happy Holidays
    {% endif %}
    
    1. Or use plain string assignments (not boolean values assignments) within 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. Still want unsing intermediary isDecember? If you would put some dummy text assignment within either clause of if/else that would work too.
    {% if month == "12" %}
      {% assign dummy = "summy" %}
      {% assign isDecember = true %}
    {% else %}
      {% assign isDecember = false %}
    {% endif %}
    
    

    Hope that helps.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search