Ternary Operators in Twig

OpenCartBot - 01 April 2026
Ternary Operators in Twig

If you work with Twig, you already know: templates should be clean, fast, and free of unnecessary PHP code. Ternary operators are the tool that lets you replace bulky {% if %} blocks with a single compact line and save dozens of lines in your templates.

Twig is used in many popular systems:

  • Symfony
  • Drupal 8+ / 10+
  • OpenCart 3.0+ and 4.x
  • Craft CMS
  • Bolt CMS, Grav, and many other PHP projects

This cheat sheet is especially useful for OpenCart developers. In this CMS, almost all templates (product.twig, category.twig, cart.twig, etc.) are built with Twig, and the ability to write short conditional expressions greatly simplifies theme customization, module development, and project maintenance.

Support for extended ternary operators was added back in Twig 1.12.0. Since then, they have become a must-have for any Twig developer.


1. Classic Ternary Operator (if — else)

{{ foo ? 'yes' : 'no' }}

2. Elvis Operator — “if it exists, output it, otherwise default”

{{ foo ?: 'no' }}

Or the full equivalent:

{{ foo ? foo : 'no' }}

3. One-sided Ternary Operator (true part only)

{{ foo ? 'yes' }}

Or explicitly:

{{ foo ? 'yes' : '' }}

4. Null Coalescing Operator ?? (since Twig 2.7.0+, for the new OpenCart releases only)

{{ foo ?? 'no' }}

Important: Returns foo only if the variable is defined and is not null. Empty values ('', 0, false, empty array) are considered valid and are not replaced.


5. default Filter — The Most Flexible Option

{{ foo|default('no') }}

Difference from ??:

  • |default replaces the value if the variable is undefined or empty (false, 0, '', null, []).
  • ?? replaces only null or an undefined variable.

In OpenCart practice, |default is used more often because many variables can be empty strings or zeros.


Comparison Table

Operator Replaces null/undefined Replaces empty values ('' , 0 , false)
foo ? 'yes' : 'no' Yes Yes
foo ?: 'no' Yes Yes
foo ? 'yes' Yes Yes
foo ?? 'no' Yes No
foo|default('no') Yes Yes

Practical Examples for OpenCart

<!-- Product price -->
<span class="price">{{ product.special ?? product.price|default('On request') }}</span>

<!-- Stock status -->
{{ product.quantity > 0 ? 'In stock' : 'Pre-order' }}

<!-- Sale badge class -->
<div class="{{ product.special ? 'product--sale' : '' }}">

Useful Tips

  1. Don’t overuse nested ternary operators — the code becomes hard to read.
  2. For complex conditions, it’s better to use {% if %} blocks or a separate macro.
  3. In Twig 3.x+, ternary operators work even more reliably with types.
  4. If you’re using OpenCart 4.x — Twig is updated there, so all the constructions above work without issues.

Bookmark this article — you’ll definitely need it the next time you refactor a template or create a new module.


Products related to this post


Related Posts