$ Currency

Ternary Operators in Twig

If you work with Twig, you 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 lin…

Ternary Operators in Twig

If you work with Twig, you 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 on Twig, and the ability to write short conditional expressions significantly simplifies theme customization, module development, and project maintenance.

Support for extended ternary operators appeared 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 (only the true branch)

{{ foo ? 'yes' }}

Or explicitly:

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

4. Null coalescing operator ?? (since Twig 2.7.0+, not suitable for old OpenCart versions)

{{ foo ?? 'no' }}

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


5. The default filter — the most flexible option

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

Difference from ??:

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

When developing OpenCart modules or templates, it is convenient to use |default, because many variables can be empty strings or zeros.


Comparison table

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

Examples for OpenCart


{{ product.quantity > 0 ? 'In stock' : 'Pre-order' }}



Useful tips

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

Bookmark this article — it will definitely come in handy during your next template refactoring or when creating a new module.

Contact via Telegram Contact via Telegram