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

2

7

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?

Jadeite answered 23/1, 2020 at 21:39 Comment(0)
S
5

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 %}
Speedometer answered 24/1, 2020 at 20:19 Comment(1)
Liquid is a joke :/Dragnet
A
1

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.

Acnode answered 4/3, 2021 at 10:50 Comment(1)
inner assign does not honor outer condition. so it's always rendered to the last assignGruel

© 2022 - 2024 — McMap. All rights reserved.