Twig Functions

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

All cards

1
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' }}
2
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 %}
3
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 %}
4
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

#}
5
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) }}
6
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" #}
7
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" #}
8
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.
9
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 #}
10
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 %}
11
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.
12
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());
13
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 %}
Study all 13 cards for free