Nothing Rhymes With Ternary

on April 25th, 2019

Antlers in Statamic 3 now supports ternary, null coalescence, Elvis, and null coalescing assignment operators. 👏 This is one of those tiny little features that represent a disproportionate amount of effort to accomplish, but one that is totally worth it because it makes developers happy and code cleaner.

Antlers, our core template language, has grown rather complex over the years, which resulted in proposed new additions to the syntax being generally pushed off to an arbitrary future date. But I'm happy to say that after a day and a half with my RegEx hat on, you can now do all these cool, new terse things in your templates!

Ternary Operator

This item is {{ is_sold ? "sold" : "available" }}.

Basic ternary operators will let you write a simple if/else statement all in one line. This is the equivalent of this longer and more annoying to write block:

This item is {{ if is_sold }}sold{{ else }}available{{ /if }}.

It also supports more complex conditions, variables as results, modifiers, and is multi-line friendly.

{{ count > 11 ? "At least a dozen!" : "Not even a dozen." }}

{{ show_title ? title : "Nothing to see here" }}

{{ capitalize_title ? title|upper : title }}

<h1>{{ show_content
    ? content
    : lorem_placeholder }}

Learn more about ternary operators in PHP.

Elvis and Null Coalescence Operators

The Elvis operator has been around since PHP 5.3, but the Null Coalescence is new in PHP 7.0. As they are two sides of the same coin, we added support for both. Technically they work the same was as our "variable fallback" logic works, but these syntaxes may be more familiar for developers with a stronger PHP background.

Strictly speaking there is a difference between ?: and ?? in that the former will throw an Exception if the variable in question is not set and the later will not, but since Antlers is already "truthy", they are functionally equivalent in Statamic land.

{{ title or site_name }}
{{ title ?? site_name }}
{{ title ?: site_name }}

Learn more about PHP's Elvis and null coalescence operators.

Null Coalescence Assignment Operator

Last but not least, we've jumped the gun on PHP 7.4 and implemented the null coalescence assignment operator, which is an even more shorthand version of the ternary operator that only cares about truthiness.

{{ show_title ??= title }}

This is functionally identical to this annoying and ugly pattern right here...

{{ if show_title }}{{ title }}{{ /if }}

Learn more about PHP's RFC for null coalescing assignment operator.

Until next time! 👋

Jack McDade
Jack McDade, Creator of Statamic
Creator of Statamic

Copyright 2020 Statamic