Don't nest or chain ternary operators

Created on 31 March 2023, over 1 year ago

Problem/Motivation

There is something wrong about nesting ternary operators in general:

And it seems even more complicated in PHP (Twig is compiled to PHP before being executed):

Unlike most (all?) other languages, the ternary operator in PHP is left-associative rather than right-associative. The left-associative behavior is generally not useful and confusing for programmers who switch between different languages.

Source: https://wiki.php.net/rfc/ternary_associativity

Proposed resolution

Only one nested operator was found:

{% set header_columns = header_columns ? header_columns : header ? header|length : 0 %}

Split it.

Other task: add parenthesis to condition with spaces to avoid the "left-associative" issue if a ternary operator is chained again.

From:
{% set button_variant = button_size == 'default' ? button_color : button_color ~ '__' ~ button_size %}

To:
{% set button_variant = (button_size == 'default') ? button_color : button_color ~ '__' ~ button_size %}

API changes

None. It is a fully backward compatible change.

📌 Task
Status

Fixed

Version

5.0

Component

Code

Created by

🇫🇷France pdureau Paris

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Production build 0.71.5 2024