Twig Code Blocks - Logical operations

Objectives
  • List Twig's logical operators
Prerequisites
  • Working with {{ }} and {% %} tags.
  • Basic programming concepts (variables (particularly booleans), operators)
Last revision:

Overview

OperatorOperationExample usageOutput
andReturns true if the left and the right operands are both true.{{ true and true }}
{{ true and false }}
true (1)
false (empty string)
orReturns true if the left or the right operand is true.{{ true or false }}
{{ true or true }}
{{ false or false }}
true
true
false
notNegates (reverses) the statement.{{ not true }}
{{ not false }}
false
true

Logical expressions are usually performed with variables that contain boolean values (true or false), or expressions that result in true or false.

Note: the following two statements are identical:

  • {% if some_var == true %}
  • {% if some_var %}

You can use both forms. Sometimes it helps to write out the explicit comparison with true/false to make the code easier to read; sometimes the opposite is true and the shorter form makes code more readable. The choice is yours.

We'll use a basic control structure (if-then-else) to illustrate the different operators.

And

{% set age = 18 %}
{% set has_license = true %}
{% if age >= 18 and has_license == true %}
Allowed to drive a car.
{% else %}
Not allowed to drive a car.
{% endif %}

Output:

Allowed to drive a car.

Or

{% set age = 16 %}
{% set has_license = false %}
{% set instructor_present = false %}
{% if (age >= 18 and has_license == true) or (age >= 16 and instructor_present) %}
Allowed to drive a car.
{% else %}
Not allowed to drive a car.
{% endif %}

Output:

Not allowed to drive a car.

Not

{% set age = 18 %}
{% set has_license = true %}

{% if age >= 18 and has_license %}
Allowed to drive a car.
{% else %}
Not allowed to drive a car.
{% endif %}

{% if age >= 18 and not has_license %}
Not allowed to drive a car.
{% else %}
Allowed to drive a car.
{% endif %}

Output:

Allowed to drive a car.
Allowed to drive a car.

Notice that the code block where the condition is reversed with not, the printed messages switched places as well.

Summary

  • The and, or, and not operators let you construct logical conditions inside Twig templates.