Twig all

76 flashcardsby Gaetan
Study these flashcardsFree · spaced repetition · iPhone, Android, Mac & web

All cards

1
abs
The abs filter returns the absolute value.

{# number = -5 #}

{{ number|abs }}

{# outputs 5 #}
2
batch
The batch filter "batches" items by returning a list of lists with the given number of items. A second parameter can be provided and used to fill in missing items

See doc for examples.
3
capitalize
The capitalize filter capitalizes a value. The first character will be uppercase, all others lowercase:

{{ 'my first car'|capitalize }}

{# outputs 'My first car' #}
4
column

The column filter returns the values from a single column in the input array.

{% set items = [{ 'fruit' : 'apple'}, {'fruit' : 'orange' }] %}

{% set fruits = items|column('fruit') %}

{# fruits now contains ['apple', 'orange'] #}
5
date
The date filter formats a date to a given format:

{{ post.published_at|date("m/d/Y") }}
6
default
The default filter returns the passed default value if the value is undefined or empty, otherwise the value of the variable:

{{ var|default('var is not defined') }}
7
date_modify
The date_modify filter modifies a date with a given modifier string:

{{ post.published_at|date_modify("+1 day")|date("m/d/Y") }}
The date_modify filter accepts strings (it must be in a format supported by the strtotime function) or DateTime instances. You can combine it with the date filter for formatting.
8
escape
The escape filter escapes a string using strategies that depend on the context.

By default, it uses the HTML escaping strategy:

{{ user.username|escape }}

For convenience, the e filter is defined as an alias:

{{ user.username|e }}
9
filter
The filter filter filters elements of a sequence or a mapping using an arrow function. The arrow function receives the value of the sequence or mapping:

{% set sizes = [34, 36, 38, 40, 42] %}

{{ sizes|filter(v => v > 38)|join(', ') }}
{# output 40, 42 #}
Combined with the for tag, it allows to filter the items to iterate over:

{% for v in sizes|filter(v => v > 38) -%}
{{ v }}
{% endfor %}
{# output 40 42 #}
10
first
The first filter returns the first "element" of a sequence, a mapping, or a string:

{{ [1, 2, 3, 4]|first }}
{# outputs 1 #}

{{ { a: 1, b: 2, c: 3, d: 4 }|first }}
{# outputs 1 #}

{{ '1234'|first }}
{# outputs 1 #}
11
format
The format filter formats a given string by replacing the placeholders (placeholders follows the sprintf notation):

{{ "I like %s and %s."|format(foo, "bar") }}

{# outputs I like foo and bar
if the foo parameter equals to the foo string. #}
12
json_encode
The json_encode filter returns the JSON representation of a value:

{{ data|json_encode() }}
13
keys

The keys filter returns the keys of an array. It is useful when you want to iterate over the keys of an array:

{% for key in array|keys %}
...
{% endfor %}
14
last

The last filter returns the last "element" of a sequence, a mapping, or a string:

{{ [1, 2, 3, 4]|last }}
{# outputs 4 #}

{{ { a: 1, b: 2, c: 3, d: 4 }|last }}
{# outputs 4 #}

{{ '1234'|last }}
{# outputs 4 #}
15
length
The length filter returns the number of items of a sequence or mapping, or the length of a string.

For objects that implement the Countable interface, length will use the return value of the count() method.

For objects that implement the __toString() magic method (and not Countable), it will return the length of the string provided by that method.

For objects that implement the Traversable interface, length will use the return value of the iterator_count() method.

For strings, mb_strlen() is used.

{% if users|length > 10 %}
...
{% endif %}
16
lower
The lower filter converts a value to lowercase:

{{ 'WELCOME'|lower }}

{# outputs 'welcome' #}
17
map
The map filter applies an arrow function to the elements of a sequence or a mapping. The arrow function receives the value of the sequence or mapping:

{% set people = [
{first: "Bob", last: "Smith"},
{first: "Alice", last: "Dupond"},
] %}

{{ people|map(p => "#{p.first} #{p.last}")|join(', ') }}
{# outputs Bob Smith, Alice Dupond #}
The arrow function also receives the key as a second argument:

{% set people = {
"Bob": "Smith",
"Alice": "Dupond",
} %}

{{ people|map((value, key) => "#{key} #{value}")|join(', ') }}
{# outputs Bob Smith, Alice Dupond #}
Note that the arrow function has access to the current context.
18
merge
The merge filter merges an array with another array:

{% set values = [1, 2] %}

{% set values = values|merge(['apple', 'orange']) %}

{# values now contains [1, 2, 'apple', 'orange'] #}
New values are added at the end of the existing ones.

The merge filter also works on hashes:

{% set items = { 'apple': 'fruit', 'orange': 'fruit', 'peugeot': 'unknown' } %}

{% set items = items|merge({ 'peugeot': 'car', 'renault': 'car' }) %}

{# items now contains { 'apple': 'fruit', 'orange': 'fruit', 'peugeot': 'car', 'renault': 'car' } #}
For hashes, the merging process occurs on the keys: if the key does not already exist, it is added but if the key already exists, its value is overridden.
19
nl2br
The nl2br filter inserts HTML line breaks before all newlines in a string:

{{ "I like Twig.\nYou will like it too."|nl2br }}
{# outputs

I like Twig.<br />
You will like it too.

#}
20
number_format
The number_format filter formats numbers. It is a wrapper around PHP's number_format function
21
raw
The raw filter marks the value as being "safe", which means that in an environment with automatic escaping enabled this variable will not be escaped if raw is the last filter applied to it:

{% autoescape %}
{{ var|raw }} {# var won't be escaped #}
{% endautoescape %}
22
reduce
The reduce filter iteratively reduces a sequence or a mapping to a single value using an arrow function, so as to reduce it to a single value. The arrow function receives the return value of the previous iteration and the current value and key of the sequence or mapping:

{% set numbers = [1, 2, 3] %}

{{ numbers|reduce((carry, v, k) => carry + v * k) }}
{# output 8 = (1*2) + (2*3) #}

The reduce filter takes an initial value as a second argument:
{{ numbers|reduce((carry, v, k) => carry + v * k, 10) }}
{# output 18 = 10 + (1*2) + (2*3)#}
Note that the arrow function has access to the current context.
23
replace
The replace filter replaces placeholders in a string (the placeholder format is free-form):

{{ "I like %this% and %that%."|replace({'%this%': fruit, '%that%': "oranges"}) }}
{# if the "fruit" variable is set to "apples", #}
{# it outputs "I like apples and oranges" #}

{# using % as a delimiter is purely conventional and optional #}
{{ "I like this and --that--."|replace({'this': fruit, '--that--': "oranges"}) }}
{# outputs "I like apples and oranges" #}
24
round
The round filter rounds a number to a given precision:

{{ 42.55|round }}
{# outputs 43 #}

{{ 42.55|round(1, 'floor') }}
{# outputs 42.5 #}
The round filter takes two optional arguments; the first one specifies the precision (default is 0) and the second the rounding method (default is common):

common rounds either up or down (rounds the value up to precision decimal places away from zero, when it is half way there -- making 1.5 into 2 and -1.5 into -2);
ceil always rounds up;
floor always rounds down.
25
slice

The slice filter extracts a slice of a sequence, a mapping, or a string:

{% for i in [1, 2, 3, 4, 5]|slice(1, 2) %}
{# will iterate over 2 and 3 #}
{% endfor %}

{{ '12345'|slice(1, 2) }}

{# outputs 23 #}
26
sort
The sort filter sorts an array:

{% for user in users|sort %}
...
{% endfor %}
Note
Internally, Twig uses the PHP asort function to maintain index association. It supports Traversable objects by transforming those to arrays.

You can pass an arrow function to sort the array:

{% set fruits = [
{ name: 'Apples', quantity: 5 },
{ name: 'Oranges', quantity: 2 },
{ name: 'Grapes', quantity: 4 },
] %}

{% for fruit in fruits|sort((a, b) => a.quantity <=> b.quantity)|column('name') %}
{{ fruit }}
{% endfor %}

{# output in this order: Oranges, Grapes, Apples #}
Note the usage of the spaceship operator to simplify the comparison.
27
spaceless
Use the spaceless filter to remove whitespace between HTML tags, not whitespace within HTML tags or whitespace in plain text:

{{
"<div>
<strong>foo</strong>
</div>
"|spaceless }}

{# output will be <div><strong>foo</strong></div> #}
You can combine spaceless with the apply tag to apply the transformation on large amounts of HTML:

{% apply spaceless %}
<div>
<strong>foo</strong>
</div>
{% endapply %}

{# output will be <div><strong>foo</strong></div> #}
This tag is not meant to "optimize" the size of the generated HTML content but merely to avoid extra whitespace between HTML tags to avoid browser rendering quirks under some circumstances.
28
split
The split filter splits a string by the given delimiter and returns a list of strings:

{% set foo = "one,two,three"|split(',') %}
{# foo contains ['one', 'two', 'three'] #}
You can also pass a limit argument:

If limit is positive, the returned array will contain a maximum of limit elements with the last element containing the rest of string;
If limit is negative, all components except the last -limit are returned;
If limit is zero, then this is treated as 1.
{% set foo = "one,two,three,four,five"|split(',', 3) %}
{# foo contains ['one', 'two', 'three,four,five'] #}
If the delimiter is an empty string, then value will be split by equal chunks. Length is set by the limit argument (one character by default).

{% set foo = "123"|split('') %}
{# foo contains ['1', '2', '3'] #}

{% set bar = "aabbcc"|split('', 2) %}
{# bar contains ['aa', 'bb', 'cc'] #}
29
striptags
The striptags filter strips SGML/XML tags and replaces adjacent whitespace characters by one space:

{{ some_html|striptags }}
You can also provide tags which should not be stripped:

{{ some_html|striptags('<br><p>') }}
In this example, the <br/>, <br>, <p>, and </p> tags won't be removed from the string.
30
title
The title filter returns a titlecased version of the value. Words will start with uppercase letters, all remaining characters are lowercase:

{{ 'my first car'|title }}

{# outputs 'My First Car' #}
31
trim
The trim filter strips whitespace (or other characters) from the beginning and end of a string:

{{ ' I like Twig. '|trim }}

{# outputs 'I like Twig.' #}

{{ ' I like Twig.'|trim('.') }}

{# outputs ' I like Twig' #}

{{ ' I like Twig. '|trim(side='left') }}

{# outputs 'I like Twig. ' #}

{{ ' I like Twig. '|trim(' ', 'right') }}

{# outputs ' I like Twig.' #}
32
upper
The upper filter converts a value to uppercase:

{{ 'welcome'|upper }}

{# outputs 'WELCOME' #}
33
url_encode
The url_encode filter percent encodes a given string as URL segment or an array as query string:

{{ "path-seg*ment"|url_encode }}
{# outputs "path-seg%2Ament" #}

{{ "string with spaces"|url_encode }}
{# outputs "string%20with%20spaces" #}

{{ {'param': 'value', 'foo': 'bar'}|url_encode }}
{# outputs "param=value&foo=bar" #}
34
reverse
The reverse filter reverses a sequence, a mapping, or a string:

{% for user in users|reverse %}
...
{% endfor %}

{{ '1234'|reverse }}

{# outputs 4321 #}
35
join
The join filter returns a string which is the concatenation of the items of a sequence:

{{ [1, 2, 3]|join }}
{# returns 123 #}
The separator between elements is an empty string per default, but you can define it with the optional first parameter:

{{ [1, 2, 3]|join('|') }}
{# outputs 1|2|3 #}
A second parameter can also be provided that will be the separator used between the last two items of the sequence:

{{ [1, 2, 3]|join(', ', ' and ') }}
{# outputs 1, 2 and 3 #}
36
attribute
The attribute function can be used to access a "dynamic" attribute of a variable:

{{ attribute(object, method) }}
{{ attribute(object, method, arguments) }}
{{ attribute(array, item) }}
In addition, the defined test can check for the existence of a dynamic attribute:

{{ attribute(object, method) is defined ? 'Method exists' : 'Method does not exist' }}
37
block
When a template uses inheritance and if you want to print a block multiple times, use the block function:

<title>{% block title %}{% endblock %}</title>

<h1>{{ block('title') }}</h1>

{% block body %}{% endblock %}
The block function can also be used to display one block from another template:

{{ block("title", "common_blocks.twig") }}
Use the defined test to check if a block exists in the context of the current template:

{% if block("footer") is defined %}
...
{% endif %}

{% if block("footer", "common_blocks.twig") is defined %}
...
{% endif %}
38
constant

constant returns the constant value for a given string:

{{ some_date|date(constant('DATE_W3C')) }}
{{ constant('Namespace\\Classname::CONSTANT_NAME') }}
You can read constants from object instances as well:

{{ constant('RSS', date) }}
Retrieve the fully qualified class name of an object:

{{ constant('class', date) }}
Use the defined test to check if a constant is defined:

{% if constant('SOME_CONST') is defined %}
...
{% endif %}
39
cycle
The cycle function cycles on an array of values:

{% set start_year = date() | date('Y') %}
{% set end_year = start_year + 5 %}

{% for year in start_year..end_year %}
{{ cycle(['odd', 'even'], loop.index0) }}
{% endfor %}

{# outputs

odd
even
odd
even
odd
even

#}
40
dump
The dump function dumps information about a template variable. This is mostly useful to debug a template that does not behave as expected by introspecting its variables:

{{ dump(user) }}
41
max
max returns the biggest value of a sequence or a set of values:

{{ max(1, 3, 2) }}
{{ max([1, 3, 2]) }}
When called with a mapping, max ignores keys and only compares values:

{{ max({2: "e", 1: "a", 3: "b", 5: "d", 4: "c"}) }}
{# returns "e" #}
42
min
min returns the lowest value of a sequence or a set of values:

{{ min(1, 3, 2) }}
{{ min([1, 3, 2]) }}
When called with a mapping, min ignores keys and only compares values:

{{ min({2: "e", 3: "a", 1: "b", 5: "d", 4: "c"}) }}
{# returns "a" #}
43
parent
When a template uses inheritance, it's possible to render the contents of the parent block when overriding a block by using the parent function:

{% extends "base.html" %}

{% block sidebar %}
<h3>Table Of Contents</h3>
...
{{ parent() }}
{% endblock %}
The parent() call will return the content of the sidebar block as defined in the base.html template.
44
random
The random function returns a random value depending on the supplied parameter type:

a random item from a sequence;
a random character from a string;
a random integer between 0 and the integer parameter (inclusive).
a random integer between the integer parameter (when negative) and 0 (inclusive).
a random integer between the first integer and the second integer parameter (inclusive).
{{ random(['apple', 'orange', 'citrus']) }} {# example output: orange #}
{{ random('ABC') }} {# example output: C #}
{{ random() }} {# example output: 15386094 (works as the native PHP mt_rand function) #}
{{ random(5) }} {# example output: 3 #}
{{ random(50, 100) }} {# example output: 63 #}
45
range

Returns a list containing an arithmetic progression of integers:

{% for i in range(0, 3) %}
{{ i }},
{% endfor %}

{# outputs 0, 1, 2, 3, #}
When step is given (as the third parameter), it specifies the increment (or decrement for negative values):

{% for i in range(0, 6, 2) %}
{{ i }},
{% endfor %}

{# outputs 0, 2, 4, 6, #}

The Twig built-in .. operator is just syntactic sugar for the range function (with a step of 1, or -1 if the start is greater than the end):

{% for i in 0..3 %}
{{ i }},
{% endfor %}
46
source
The source function returns the content of a template without rendering it:

{{ source('template.html') }}
{{ source(some_var) }}
When you set the ignore_missing flag, Twig will return an empty string if the template does not exist:

{{ source('template.html', ignore_missing = true) }}
The function uses the same template loaders as the ones used to include templates. So, if you are using the filesystem loader, the templates are looked for in the paths defined by it.
47
template_from_string
The template_from_string function loads a template from a string:

{{ include(template_from_string("Hello {{ name }}")) }}
{{ include(template_from_string(page.template)) }}
To ease debugging, you can also give the template a name that will be part of any related error message:

{{ include(template_from_string(page.template, "template for page " ~ page.name)) }}
Note
The template_from_string function is not available by default.

On Symfony projects, you need to load it in your services.yaml file:

services:
Twig\Extension\StringLoaderExtension:
or services.php file:

$services->set(\Twig\Extension\StringLoaderExtension::class); Otherwise, add the extension explicitly on the Twig environment: use Twig\Extension\StringLoaderExtension; $twig = new \Twig\Environment(...);
$twig->addExtension(new StringLoaderExtension());
48
date
Converts an argument to a date to allow date comparison:

{% if date(user.created_at) < date('-2days') %}
{# do something #}
{% endif %}
The argument must be in one of PHP’s supported date and time formats.

You can pass a timezone as the second argument:

{% if date(user.created_at) < date('-2days', 'Europe/Paris') %}
{# do something #}
{% endif %}
If no argument is passed, the function returns the current date:

{% if date(user.created_at) < date() %}
{# always! #}
{% endif %}
49
apply
The apply tag allows you to apply Twig filters on a block of template data.
50
autoescape
Whether automatic escaping is enabled or not, you can mark a section of a template to be escaped or not by using the autoescape tag.

/!\ Complex tag, see doc for details.
51
block
Blocks are used for inheritance and act as placeholders and replacements at the same time. They are documented in detail in the documentation for the extends tag.

Block names must consist of alphanumeric characters, and underscores. The first char can't be a digit and dashes are not permitted.

/!\ Complex tag, see doc for details.
52
deprecated
Twig generates a deprecation notice (via a call to the trigger_error() PHP function) where the deprecated tag is used in a template.

See doc for details
53
do
The do tag works exactly like the regular variable expression ({{ ... }}) just that it doesn't print anything:

{% do 1 + 2 %}
54
embed
The embed tag combines the behavior of include and extends. It allows you to include another template's contents, just like include does. But it also allows you to override any block defined inside the included template, like when extending a template.
See doc for details
55
extends
The extends tag can be used to extend a template from another one.

/!\ Complex tag, see doc for details.
https://twig.symfony.com/doc/3.x/tags/extends.html
56
flush
The flush tag tells Twig to flush the output buffer:

{% flush %}
57
for
Loop over each item in a sequence.
Inside of a for loop block you can access some special variables:

loop.index The current iteration of the loop. (1 indexed)
loop.index0 The current iteration of the loop. (0 indexed)
loop.revindex The number of iterations from the end of the loop (1 indexed)
loop.revindex0 The number of iterations from the end of the loop (0 indexed)
loop.first True if first iteration
loop.last True if last iteration
loop.length The number of items in the sequence
loop.parent The parent context

/!\ Complex tag, see doc for details.
58
include
The include statement includes a template and outputs the rendered content of that file

/!\ Complex tag, see doc for details.
59
import
The import tag imports macro names in a local variable.

The tag is documented in detail in the documentation for the macro tag.
60
macro
Macros are comparable with functions in regular programming languages. They are useful to reuse template fragments to not repeat yourself.

Macros are defined in regular templates.

/!\ Complex tag, see doc for details.
61
sandbox
The sandbox tag can be used to enable the sandboxing mode for an included template, when sandboxing is not enabled globally for the Twig environment:

{% sandbox %}
{% include 'user.html' %}
{% endsandbox %}
62
set
Inside code blocks you can also assign values to variables. Assignments use the set tag and can have multiple targets.

Here is how you can assign the bar value to the foo variable:

{% set foo = 'bar' %}
63
use
Horizontal reuse is a way to achieve the same goal as multiple inheritance, but without the associated complexity:

{% extends "base.html" %}

{% use "blocks.html" %}

{% block title %}{% endblock %}
{% block content %}{% endblock %}
The use statement tells Twig to import the blocks defined in blocks.html into the current template (it's like macros, but for blocks):

{# blocks.html #}

{% block sidebar %}{% endblock %}
In this example, the use statement imports the sidebar block into the main template. The code is mostly equivalent to the following one (the imported blocks are not outputted automatically):

{% extends "base.html" %}

{% block sidebar %}{% endblock %}
{% block title %}{% endblock %}
{% block content %}{% endblock %}

/!\ Complex tag, see doc for details.
64
verbatim
The verbatim tag marks sections as being raw text that should not be parsed. For example to put Twig syntax as example into a template you can use this snippet:

{% verbatim %}
<ul>
{% for item in seq %}
<li>{{ item }}</li>
{% endfor %}
<l>
{% endverbatim %}
65
with
Use the with tag to create a new inner scope. Variables set within this scope are not visible outside of the scope:

{% with %}
{% set foo = 42 %}
{{ foo }} {# foo is 42 here #}
{% endwith %}
foo is not visible here any longer
66
if
The if statement in Twig is comparable with the if statements of PHP.

In the simplest form you can use it to test if an expression evaluates to true
67
from
The from tag imports macro names into the current namespace. The tag is documented in detail in the documentation for the macro tag.
68
constant
constant checks if a variable has the exact same value as a constant. You can use either global constants or class constants:

{% if post.status is constant('Post::PUBLISHED') %}
the status attribute is exactly the same as Post::PUBLISHED
{% endif %}
You can test constants from object instances as well:

{% if post.status is constant('PUBLISHED', post) %}
the status attribute is exactly the same as Post::PUBLISHED
{% endif %}
69
defined
defined checks if a variable is defined in the current context. This is very useful if you use the strict_variables option:

{# defined works with variable names #}
{% if foo is defined %}
...
{% endif %}

{# and attributes on variables names #}
{% if foo.bar is defined %}
...
{% endif %}

{% if foo['bar'] is defined %}
...
{% endif %}
When using the defined test on an expression that uses variables in some method calls, be sure that they are all defined first:

{% if var is defined and foo.method(var) is defined %}
...
{% endif %}
70
even
even returns true if the given number is even:

{{ var is even }}
71
iterable
iterable checks if a variable is an array or a traversable object:

{# evaluates to true if the foo variable is iterable #}
{% if users is iterable %}
{% for user in users %}
Hello {{ user }}!
{% endfor %}
{% else %}
{# users is probably a string #}
Hello {{ users }}!
{% endif %}
72
null

null returns true if the variable is null:

{{ var is null }}
73
odd
odd returns true if the given number is odd:

{{ var is odd }}
74
same as
same as checks if a variable is the same as another variable. This is equivalent to === in PHP:

{% if foo.attribute is same as(false) %}
the foo attribute really is the 'false' PHP value
{% endif %}
75
empty
empty checks if a variable is an empty string, an empty array, an empty hash, exactly false, or exactly null.

For objects that implement the Countable interface, empty will check the return value of the count() method.

For objects that implement the __toString() magic method (and not Countable), it will check if an empty string is returned.

{% if foo is empty %}
...
{% endif %}
76
divisible by
divisible by checks if a variable is divisible by a number:

{% if loop.index is divisible by(3) %}
...
{% endif %}
Study all 76 cards for free