If you've worked with Twig in Drupal before, you may have come across the need to create conditional expressions. One way to achieve this is by using the ternary operator, which allows you to write more concise and readable code. In this blog post, we'll show you how to use the ternary operator in Twig in Drupal 10.
The ternary operator is a shorthand way of writing a conditional expression. It takes three operands: a condition to test, a value to return if the condition is true, and a value to return if the condition is false. The syntax of the ternary operator in Twig is as follows:
condition ? value_if_true : value_if_false
The condition is evaluated first. If it is true, the value_if_true expression is returned; otherwise, the value_if_false expression is returned.
To use the ternary operator in Twig, you can simply replace an if/else statement with the ternary operator. Here's an example:
{% if foo %}
Hello, {{ foo }}!
{% else %}
Hello, world!
{% endif %}
This if/else statement can be replaced with the ternary operator as follows:
Hello, {{ foo ? foo ~ '!' : 'world!' }}
In this example, if the "foo" variable is defined, its value is used along with an exclamation mark to create a personalized greeting. Otherwise, the default greeting "Hello, world!" is used.
In Drupal 10, you can use the ternary operator in the same way as in regular Twig code. Here's an example of how you can use the ternary operator to create an array of CSS class names based on some conditions:
{% set paragraph_parent = paragraph.getParentEntity() %}
{% set column_width = paragraph_parent.field_width.0.value %}
{% set classes = [
'paragraph',
'paragraph--type--' ~ paragraph.bundle|clean_class,
view_mode ? 'paragraph--view-mode--' ~ view_mode|clean_class,
not paragraph.isPublished() ? 'paragraph--unpublished',
column_width == 'two' ? 'col-12 col-md-6 col-lg-4',
column_width == 'three' ? 'col-12 col-md-6'
] %}
In this example, an array called "classes" is defined using the set keyword. The array contains a list of CSS class names based on some conditions. The ternary operator is used to create conditional expressions for the "view_mode" and "column_width" variables.