Skip to main content

Syntax & Operators

Delimiters​

Twig uses three types of delimiters:

DelimiterPurposeExample
{{ ... }}Output an expression{{ user.name }}
{% ... %}Execute statements{% if active %}...{% endif %}
{# ... #}Comments (not included in HTML){# Template note #}

Variables​

Accessing properties​

Accessing properties
{# Dot notation #}
{{ user.name }}
{{ user.address.city }}

{# Bracket notation #}
{{ user['name'] }}
{{ data['key-with-dashes'] }}

{# Method calls #}
{{ user.getName() }}
{{ items.count() }}

{# Null-safe operator (Twig 3.x) #}
{{ user?.address?.city }}
{# Returns null instead of an error if user or address is null #}

Global variables​

Global variables
{# Current template name #}
{{ _self }}

{# Current context (all variables) #}
{{ dump(_context) }}

{# Charset #}
{{ _charset }}

Literals​

Strings​

Strings
{# Single or double quotes #}
{{ "Hello" }}
{{ 'World' }}

{# String interpolation (double quotes only) #}
{{ "Hello #{user.name}!" }}
{{ "Total: #{price * quantity} USD" }}

{# Escaping #}
{{ "String with \"quotes\"" }}
{{ 'It\'s fine' }}

Numbers​

Numbers
{{ 42 }}
{{ 3.14 }}
{{ -17 }}

Booleans and null​

Booleans and null
{{ true }}
{{ false }}
{{ null }}
{{ none }} {# alias for null #}

Arrays​

Arrays
{# Creating an array #}
{% set items = ['apple', 'banana', 'cherry'] %}
{% set matrix = [[1, 2], [3, 4]] %}

{# Accessing by index #}
{{ items[0] }} {# apple #}

Hashes (associative arrays)​

Hashes (associative arrays)
{% set user = {name: 'John', age: 30, 'key-with-dashes': true} %}

{# Keys can be strings or expressions #}
{% set data = {
(variable): 'value',
'static-key': 'value'
} %}

{{ user.name }} {# John #}

Operators​

Arithmetic​

OperatorDescriptionExample
+Addition{{ 1 + 2 }} -> 3
-Subtraction{{ 5 - 3 }} -> 2
*Multiplication{{ 2 * 3 }} -> 6
/Division{{ 10 / 3 }} -> 3.333...
//Integer division{{ 10 // 3 }} -> 3
%Modulo{{ 10 % 3 }} -> 1
**Exponentiation{{ 2 ** 10 }} -> 1024

Comparison​

OperatorDescription
==Equal
!=Not equal
<Less than
>Greater than
<=Less than or equal
>=Greater than or equal
===Strict comparison (type and value)
<=>Spaceship (returns -1, 0, 1)

Logical​

OperatorDescriptionExample
andLogical AND{% if a and b %}
orLogical OR{% if a or b %}
notLogical NOT{% if not active %}
xorExclusive OR{% if a xor b %}

Bitwise​

OperatorDescription
b-andBitwise AND
b-orBitwise OR
b-xorBitwise XOR

String​

String
{# Concatenation using ~ #}
{{ 'Hello ' ~ user.name ~ '!' }}
{{ 'Price: ' ~ price ~ ' USD' }}

Containment operator​

Containment operator
{# in - check for array membership or substring #}
{% if 'admin' in user.roles %}
{% if 'hello' in message %}

{# not in #}
{% if user.status not in ['banned', 'deleted'] %}

{# starts with / ends with #}
{% if filename starts with 'temp_' %}
{% if email ends with '@gmail.com' %}

{# matches - regular expression #}
{% if login matches '/^[a-zA-Z0-9_]{4,16}$/' %}

Ternary operator​

Ternary operator
{# Full form #}
{{ active ? 'Yes' : 'No' }}

{# Short form (Elvis) #}
{{ username ?: 'Anonymous' }}

{# Null-coalescing operator #}
{{ user.name ?? 'Guest' }}
{{ data['key'] ?? config.default ?? 'fallback' }}

Range​

Range
{# Creating a sequence #}
{% for i in 0..10 %}
{{ i }}
{% endfor %}

{% for letter in 'a'..'z' %}
{{ letter }}
{% endfor %}

Spread operator​

Spread operator
{# Spreading an array into arguments #}
{% set args = ['one', 'two'] %}
{{ myMacro(...args) }}

{# Merging arrays #}
{% set merged = [...array1, ...array2, 'extra'] %}

{# Spreading a hash #}
{% set defaults = {class: 'btn', type: 'button'} %}
{% set attrs = {...defaults, id: 'submit'} %}

Whitespace control​

Whitespace control
{# Removing whitespace using a hyphen #}
{%- if active -%}
Active
{%- endif -%}

{# Removing line breaks using a tilde #}
{%~ if active ~%}
Active
{%~ endif ~%}

{# Can be combined with output delimiters #}
{{- variable -}}
SymbolPositionEffect
-Left ({%-)Removes whitespace before the tag
-Right (-%})Removes whitespace after the tag
~Left ({%~)Removes only line breaks before the tag
~Right (~%})Removes only line breaks after the tag

Named arguments​

Named arguments
{# Filters with named arguments #}
{{ 'hello'|replace({'h': 'H'}) }}
{{ number|number_format(decimals: 2, decimal_point: ',', thousands_separator: ' ') }}

{# Functions with named arguments #}
{{ include('@common/card.html.twig', with_context: false) }}