Understanding operators in Twig
In Twig, operators are used to perform various operations within templates, such as comparing values, performing arithmetic calculations, or manipulating data. Understanding how operators work in Twig can help you create more dynamic and functional templates on your theme.
Types of operators in Twig
Twig provides several types of operators that you can use to control the logic within templates.
Arithmetic operators
Arithmetic operators allow you to perform basic mathematical operations:
+
(addition), e.g.{{ 3 + 3 }}
results in 6-
(subtraction), e.g.{{ 10 - 4 }}
results in 6*
(multiplication), e.g.{{ 2 * 3 }}
results in 6/
(division), e.g.{{ 9 / 3 }}
results in 3%
(modulus, remainder of a division), e.g.{{ 7 % 3 }}
results in 1
Comparison operators
Comparison operators are used to compare values and are often used in conditional statements:
==
(equals), e.g.{{ 5 == 5 }}
results in true!=
(not equal), e.g.{{ 5 != 3 }}
results in true<
(less than), e.g.{{ 3 < 5 }}
results in true>
(greater than), e.g.{{ 5 > 3 }}
results in true<=
(less than or equal to), e.g.{{ 5 <= 5 }}
results in true>=
(greater than or equal to), e.g.{{ 5 >= 4 }}
results in true
Logical operators
Logical operators are used to combine multiple conditions or invert conditions:
and
(logical AND), e.g.{{ true and false }}
results in falseor
(logical OR), e.g.{{ true or false }}
results in truenot
(logical NOT), e.g.{{ not true }}
results in false
String operators
Twig allows you to strings:
~
(concatenation), e.g.{{ 'Hello ' ~ 'World' }}
results in Hello World
Miscellaneous operators
There are other operators in Twig that serve specific purposes:
..
(range operator, used to create a sequence of numbers), e.g.{{ 1..5 }}
results in 1, 2, 3, 4, 5is
(used to test if a variable matches a specific condition), e.g.{{ variable is defined }}
checks ifvariable
is defined
Using operators in ShopWired
When customising templates with Twig, these operators can be used in a range of different scenarios to handle data.
For a comprehensive list of operators and more detailed examples, you can visit the official Twig documentation on operators.