Skip to content

Conversation

@jg-rp
Copy link
Owner

@jg-rp jg-rp commented Mar 9, 2025

It looks like Shopify are considering/experimenting with conditional expressions in Liquid. This PR implements that same syntax and behaviour in Python Liquid.

Here we're talking about in line control structures that can be used in output statements, assignment expressions and as arguments to tags and filters. Liquid currently supports the following expressions in these locations.

  • literals (strings, integers, floats, true, false, nil/null)
  • range expressions* ((1..5))
  • variable names/paths (foo.bar[0])
  • reserved words (empty, blank)

Collectively, in Python Liquid, we call these primitive expressions. They are the small building blocks that make up all other expressions.

Shopify/Liquid #1922 (draft) adds support for compound expressions in output statements, assignment expressions and as arguments to tags and filters. These compound expressions combine primitives with Boolean operators (and and or) and/or comparison operators (==, >, >=, etc.).

Boolean operator semantics

In this example, the variable x will be set to the value at a if a is truthy, or the value at b if a is falsy.

{% assign x = a or b %}

This is logically equivalent to if a then a else b or a if a else b using ternary condition syntax.

And here, with the and operator, the variable x will be set to the value at b if a is truthy, or the value at a if a is falsy, which is logically equivalent to if a then b else a or b if a else a using ternary condition syntax.

{% assign x = a and b %}

With short-circuit evaluation, these Boolean operator semantics are sometimes called "last value", as the result is the value of the last sub expression to be evaluated.

Note

Outstanding issue Shopify/liquid #1034 might limit the usefulness of in line Boolean operators for some deployments.

This experiment

As we already support ternary condition syntax, we'll conceptually treat expressions including Boolean operators as a shorthand form of the more general ternary expression.

We'll define a primary expression to replace most uses of primitive expression that is effectively equivalent to the current parse_logical_primitive() function, just that the resulting expression evaluates to the last value rather than a Boolean.

Existing comparison operators should work unchanged, because they always evaluate to a Boolean value.

@jg-rp
Copy link
Owner Author

jg-rp commented Apr 22, 2025

Also, or is already a reserved word in {% when %} tags, so would need some special attention.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants