Twig PDF
Twig PDF
Twig PDF
Some pages ("foo" and "bar") share the same content structure - two vertically stacked boxes:
1
2
3
4
5
6
7
8
9
10
11
12
page layout
block "content"
block "top"
block "bottom"
While other pages ("boom" and "baz") share a different content structure - two boxes side by side:
1
2
3
4
5
6
7
8
9
10
11
12
page layout
block "content"
block block
"left" "right"
Without the embed tag, you have two ways to design your templates:
Create two "intermediate" base templates that extend the master layout template: one
with vertically stacked boxes to be used by the "foo" and "bar" pages and another one
with side-by-side boxes for the "boom" and "baz" pages.
Embed the markup for the top/bottom and left/right boxes into each page template
directly.
These two solutions do not scale well because they each have a major drawback:
The first solution may indeed work for this simplified example. But imagine we add
a sidebar, which may again contain different, recurring structures of content. Now we
would need to create intermediate base templates for all occurring combinations of
content structure and sidebar structure... and so on.
The second solution involves duplication of common code with all its negative
consequences: any change involves finding and editing all affected copies of the
PDF brought to you by
generated on April 16, 2014
Chapter 12: embed | 63
Listing 12-5
Listing 12-6
Listing 12-7
structure, correctness has to be verified for each copy, copies may go out of sync by
careless modifications etc.
In such a situation, the embed tag comes in handy. The common layout code can live in a single base
template, and the two different content structures, let's call them "micro layouts" go into separate
templates which are embedded as necessary:
Page template foo.twig:
1
2
3
4
5
6
7
8
9
10
11
12
13
{% extends "layout_skeleton.twig" %}
{% block content %}
{% embed "vertical_boxes_skeleton.twig" %}
{% block top %}
Some content for the top box
{% endblock %}
{% block bottom %}
Some content for the bottom box
{% endblock %}
{% endembed %}
{% endblock %}
And here is the code for vertical_boxes_skeleton.twig:
1
2
3
4
5
6
7
8
9
10
11
<div class="top_box">
{% block top %}
Top box default content
{% endblock %}
</div>
<div class="bottom_box">
{% block bottom %}
Bottom box default content
{% endblock %}
</div>
The goal of the vertical_boxes_skeleton.twig template being to factor out the HTML markup for the
boxes.
The embed tag takes the exact same arguments as the include tag:
1
2
3
4
5
6
7
8
9
10
11
{% embed "base" with {'foo': 'bar'} %}
...
{% endembed %}
{% embed "base" with {'foo': 'bar'} only %}
...
{% endembed %}
{% embed "base" ignore missing %}
...
{% endembed %}
PDF brought to you by
generated on April 16, 2014
Chapter 12: embed | 64
As embedded templates do not have "names", auto-escaping strategies based on the template
"filename" won't work as expected if you change the context (for instance, if you embed a CSS/
JavaScript template into an HTML one). In that case, explicitly set the default auto-escaping
strategy with the autoescape tag.
include
PDF brought to you by
generated on April 16, 2014
Chapter 12: embed | 65
Listing 13-1
Chapter 13
extends
The extends tag can be used to extend a template from another one.
Like PHP, Twig does not support multiple inheritance. So you can only have one extends tag called
per rendering. However, Twig supports horizontal reuse.
Let's define a base template, base.html, which defines a simple HTML skeleton document:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<!DOCTYPE html>
<html>
<head>
{% block head %}
<link rel="stylesheet" href="style.css" />
<title>{% block title %}{% endblock %} - My Webpage</title>
{% endblock %}
</head>
<body>
<div id="content">{% block content %}{% endblock %}</div>
<div id="footer">
{% block footer %}
© Copyright 2011 by <a href="http://domain.invalid/">you</a>.
{% endblock %}
</div>
</body>
</html>
In this example, the block tags define four blocks that child templates can fill in.
All the block tag does is to tell the template engine that a child template may override those portions of
the template.
Child Template
A child template might look like this:
PDF brought to you by
generated on April 16, 2014
Chapter 13: extends | 66
Listing 13-2
Listing 13-3
Listing 13-4
Listing 13-5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
{% extends "base.html" %}
{% block title %}Index{% endblock %}
{% block head %}
{{ parent() }}
<style type="text/css">
.important { color: #336699; }
</style>
{% endblock %}
{% block content %}
<h1>Index</h1>
<p class="important">
Welcome on my awesome homepage.
</p>
{% endblock %}
The extends tag is the key here. It tells the template engine that this template "extends" another template.
When the template system evaluates this template, first it locates the parent. The extends tag should be
the first tag in the template.
Note that since the child template doesn't define the footer block, the value from the parent template is
used instead.
You can't define multiple block tags with the same name in the same template. This limitation exists
because a block tag works in "both" directions. That is, a block tag doesn't just provide a hole to fill - it
also defines the content that fills the hole in the parent. If there were two similarly-named block tags in a
template, that template's parent wouldn't know which one of the blocks' content to use.
If you want to print a block multiple times you can however use the block function:
1
2
3
<title>{% block title %}{% endblock %}</title>
<h1>{{ block('title') }}</h1>
{% block body %}{% endblock %}
Parent Blocks
It's possible to render the contents of the parent block by using the parent function. This gives back the
results of the parent block:
1
2
3
4
5
{% block sidebar %}
<h3>Table Of Contents</h3>
...
{{ parent() }}
{% endblock %}
Named Block End-Tags
Twig allows you to put the name of the block after the end tag for better readability:
1
2
3
{% block sidebar %}
{% block inner_sidebar %}
...
PDF brought to you by
generated on April 16, 2014
Chapter 13: extends | 67
Listing 13-6
Listing 13-7
Listing 13-8
Listing 13-9
Listing 13-10
Listing 13-11
4
5
{% endblock inner_sidebar %}
{% endblock sidebar %}
Of course, the name after the endblock word must match the block name.
Block Nesting and Scope
Blocks can be nested for more complex layouts. Per default, blocks have access to variables from outer
scopes:
1
2
3
{% for item in seq %}
<li>{% block loop_item %}{{ item }}{% endblock %}</li>
{% endfor %}
Block Shortcuts
For blocks with few content, it's possible to use a shortcut syntax. The following constructs do the same:
1
2
3
{% block title %}
{{ page_title|title }}
{% endblock %}
1 {% block title page_title|title %}
Dynamic Inheritance
Twig supports dynamic inheritance by using a variable as the base template:
1 {% extends some_var %}
If the variable evaluates to a Twig_Template object, Twig will use it as the parent template:
1
2
3
4
5
// {% extends layout %}
$layout = $twig->loadTemplate('some_layout_template.twig');
$twig->display('template.twig', array('layout' => $layout));
New in version 1.2: The possibility to pass an array of templates has been added in Twig 1.2.
You can also provide a list of templates that are checked for existence. The first template that exists will
be used as a parent:
1 {% extends ['layout.html', 'base_layout.html'] %}
PDF brought to you by
generated on April 16, 2014
Chapter 13: extends | 68
Listing 13-12
Listing 13-13
Listing 13-14
Listing 13-15
Listing 13-16
Conditional Inheritance
As the template name for the parent can be any valid Twig expression, it's possible to make the
inheritance mechanism conditional:
1 {% extends standalone ? "minimum.html" : "base.html" %}
In this example, the template will extend the "minimum.html" layout template if the standalone variable
evaluates to true, and "base.html" otherwise.
How blocks work?
A block provides a way to change how a certain part of a template is rendered but it does not interfere in
any way with the logic around it.
Let's take the following example to illustrate how a block works and more importantly, how it does not
work:
1
2
3
4
5
6
7
8
{# base.twig #}
{% for post in posts %}
{% block post %}
<h1>{{ post.title }}</h1>
<p>{{ post.body }}</p>
{% endblock %}
{% endfor %}
If you render this template, the result would be exactly the same with or without the block tag. The
block inside the for loop is just a way to make it overridable by a child template:
1
2
3
4
5
6
7
8
9
10
{# child.twig #}
{% extends "base.twig" %}
{% block post %}
<article>
<header>{{ post.title }}</header>
<section>{{ post.text }}</section>
</article>
{% endblock %}
Now, when rendering the child template, the loop is going to use the block defined in the child template
instead of the one defined in the base one; the executed template is then equivalent to the following one:
1
2
3
4
5
6
{% for post in posts %}
<article>
<header>{{ post.title }}</header>
<section>{{ post.text }}</section>
</article>
{% endfor %}
Let's take another example: a block included within an if statement:
PDF brought to you by
generated on April 16, 2014
Chapter 13: extends | 69
Listing 13-17
1
2
3
4
5
6
7
{% if posts is empty %}
{% block head %}
{{ parent() }}
<meta name="robots" content="noindex, follow">
{% endblock head %}
{% endif %}
Contrary to what you might think, this template does not define a block conditionally; it just makes
overridable by a child template the output of what will be rendered when the condition is true.
If you want the output to be displayed conditionally, use the following instead:
1
2
3
4
5
6
7
{% block head %}
{{ parent() }}
{% if posts is empty %}
<meta name="robots" content="noindex, follow">
{% endif %}
{% endblock head %}
block, block, parent, use
PDF brought to you by
generated on April 16, 2014
Chapter 13: extends | 70
Listing 14-1
Chapter 14
flush
New in version 1.5: The flush tag was added in Twig 1.5.
The flush tag tells Twig to flush the output buffer:
1 {% flush %}
Internally, Twig uses the PHP flush
1
function.
1. http://php.net/flush
PDF brought to you by
generated on April 16, 2014
Chapter 14: flush | 71
Listing 15-1
Listing 15-2
Listing 15-3
Listing 15-4
Chapter 15
for
Loop over each item in a sequence. For example, to display a list of users provided in a variable called
users:
1
2
3
4
5
6
<h1>Members</h1>
<ul>
{% for user in users %}
<li>{{ user.username|e }}</li>
{% endfor %}
</ul>
A sequence can be either an array or an object implementing the Traversable interface.
If you do need to iterate over a sequence of numbers, you can use the .. operator:
1
2
3
{% for i in 0..10 %}
* {{ i }}
{% endfor %}
The above snippet of code would print all numbers from 0 to 10.
It can be also useful with letters:
1
2
3
{% for letter in 'a'..'z' %}
* {{ letter }}
{% endfor %}
The .. operator can take any expression at both sides:
PDF brought to you by
generated on April 16, 2014
Chapter 15: for | 72
Listing 15-5
Listing 15-6
1
2
3
{% for letter in 'a'|upper..'z'|upper %}
* {{ letter }}
{% endfor %}
The loop variable
Inside of a for loop block you can access some special variables:
Variable Description
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
1
2
3
{% for user in users %}
{{ loop.index }} - {{ user.username }}
{% endfor %}
The loop.length, loop.revindex, loop.revindex0, and loop.last variables are only available
for PHP arrays, or objects that implement the Countable interface. They are also not available
when looping with a condition.
New in version 1.2: The if modifier support has been added in Twig 1.2.
Adding a condition
Unlike in PHP, it's not possible to break or continue in a loop. You can however filter the sequence
during iteration which allows you to skip items. The following example skips all the users which are not
active:
1
2
3
4
5
<ul>
{% for user in users if user.active %}
<li>{{ user.username|e }}</li>
{% endfor %}
</ul>
The advantage is that the special loop variable will count correctly thus not counting the users not
iterated over. Keep in mind that properties like loop.last will not be defined when using loop
conditions.
PDF brought to you by
generated on April 16, 2014
Chapter 15: for | 73
Listing 15-7
Listing 15-8
Listing 15-9
Listing 15-10
Using the loop variable within the condition is not recommended as it will probably not be doing
what you expect it to. For instance, adding a condition like loop.index > 4 won't work as the
index is only incremented when the condition is true (so the condition will never match).
The else Clause
If no iteration took place because the sequence was empty, you can render a replacement block by using
else:
1
2
3
4
5
6
7
<ul>
{% for user in users %}
<li>{{ user.username|e }}</li>
{% else %}
<li><em>no user found</em></li>
{% endfor %}
</ul>
Iterating over Keys
By default, a loop iterates over the values of the sequence. You can iterate on keys by using the keys filter:
1
2
3
4
5
6
<h1>Members</h1>
<ul>
{% for key in users|keys %}
<li>{{ key }}</li>
{% endfor %}
</ul>
Iterating over Keys and Values
You can also access both keys and values:
1
2
3
4
5
6
<h1>Members</h1>
<ul>
{% for key, user in users %}
<li>{{ key }}: {{ user.username|e }}</li>
{% endfor %}
</ul>
Iterating over a Subset
You might want to iterate over a subset of values. This can be achieved using the slice filter:
1
2
3
<h1>Top Ten Members</h1>
<ul>
{% for user in users|slice(0, 10) %}
PDF brought to you by
generated on April 16, 2014
Chapter 15: for | 74
4
5
6
<li>{{ user.username|e }}</li>
{% endfor %}
</ul>
PDF brought to you by
generated on April 16, 2014
Chapter 15: for | 75
Chapter 16
from
The from tag imports macro names into the current namespace. The tag is documented in detail in the
documentation for the import tag.
macro, import
PDF brought to you by
generated on April 16, 2014
Chapter 16: from | 76
Listing 17-1
Listing 17-2
Listing 17-3
Chapter 17
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:
1
2
3
{% if online == false %}
<p>Our website is in maintenance mode. Please, come back later.</p>
{% endif %}
You can also test if an array is not empty:
1
2
3
4
5
6
7
{% if users %}
<ul>
{% for user in users %}
<li>{{ user.username|e }}</li>
{% endfor %}
</ul>
{% endif %}
If you want to test if the variable is defined, use if users is defined instead.
For multiple branches elseif and else can be used like in PHP. You can use more complex
expressions there too:
1
2
3
4
5
6
7
{% if kenny.sick %}
Kenny is sick.
{% elseif kenny.dead %}
You killed Kenny! You bastard!!!
{% else %}
Kenny looks okay --- so far
{% endif %}
PDF brought to you by
generated on April 16, 2014
Chapter 17: if | 77
Listing 18-1
Listing 18-2
Listing 18-3
Chapter 18
import
Twig supports putting often used code into macros. These macros can go into different templates and get
imported from there.
There are two ways to import templates. You can import the complete template into a variable or request
specific macros from it.
Imagine we have a helper module that renders forms (called forms.html):
1
2
3
4
5
6
7
{% macro input(name, value, type, size) %}
<input type="{{ type|default('text') }}" name="{{ name }}" value="{{ value|e }}"
size="{{ size|default(20) }}" />
{% endmacro %}
{% macro textarea(name, value, rows, cols) %}
<textarea name="{{ name }}" rows="{{ rows|default(10) }}" cols="{{ cols|default(40)
}}">{{ value|e }}</textarea>
{% endmacro %}
The easiest and most flexible is importing the whole module into a variable. That way you can access the
attributes:
1
2
3
4
5
6
7
8
9
{% import 'forms.html' as forms %}
<dl>
<dt>Username</dt>
<dd>{{ forms.input('username') }}</dd>
<dt>Password</dt>
<dd>{{ forms.input('password', null, 'password') }}</dd>
</dl>
<p>{{ forms.textarea('comment') }}</p>
Alternatively you can import names from the template into the current namespace:
1
2
{% from 'forms.html' import input as input_field, textarea %}
PDF brought to you by
generated on April 16, 2014
Chapter 18: import | 78
3
4
5
6
7
8
9
<dl>
<dt>Username</dt>
<dd>{{ input_field('username') }}</dd>
<dt>Password</dt>
<dd>{{ input_field('password', '', 'password') }}</dd>
</dl>
<p>{{ textarea('comment') }}</p>
To import macros from the current file, use the special _self variable for the source.
macro, from
PDF brought to you by
generated on April 16, 2014
Chapter 18: import | 79
Listing 19-1
Listing 19-2
Listing 19-3
Listing 19-4
Chapter 19
include
The include statement includes a template and returns the rendered content of that file into the current
namespace:
1
2
3
{% include 'header.html' %}
Body
{% include 'footer.html' %}
Included templates have access to the variables of the active context.
If you are using the filesystem loader, the templates are looked for in the paths defined by it.
You can add additional variables by passing them after the with keyword:
1
2
3
4
5
{# template.html will have access to the variables from the current context and the
additional ones provided #}
{% include 'template.html' with {'foo': 'bar'} %}
{% set vars = {'foo': 'bar'} %}
{% include 'template.html' with vars %}
You can disable access to the context by appending the only keyword:
1
2
{# only the foo variable will be accessible #}
{% include 'template.html' with {'foo': 'bar'} only %}
1
2
{# no variables will be accessible #}
{% include 'template.html' only %}
When including a template created by an end user, you should consider sandboxing it. More
information in the Twig for Developers chapter and in the sandbox tag documentation.
The template name can be any valid Twig expression:
PDF brought to you by
generated on April 16, 2014
Chapter 19: include | 80
Listing 19-5
Listing 19-6
Listing 19-7
Listing 19-8
1
2
{% include some_var %}
{% include ajax ? 'ajax.html' : 'not_ajax.html' %}
And if the expression evaluates to a Twig_Template object, Twig will use it directly:
1
2
3
4
5
// {% include template %}
$template = $twig->loadTemplate('some_template.twig');
$twig->loadTemplate('template.twig')->display(array('template' => $template));
New in version 1.2: The ignore missing feature has been added in Twig 1.2.
You can mark an include with ignore missing in which case Twig will ignore the statement if the
template to be included does not exist. It has to be placed just after the template name. Here some valid
examples:
1
2
3
{% include 'sidebar.html' ignore missing %}
{% include 'sidebar.html' ignore missing with {'foo': 'bar'} %}
{% include 'sidebar.html' ignore missing only %}
New in version 1.2: The possibility to pass an array of templates has been added in Twig 1.2.
You can also provide a list of templates that are checked for existence before inclusion. The first template
that exists will be included:
1 {% include ['page_detailed.html', 'page.html'] %}
If ignore missing is given, it will fall back to rendering nothing if none of the templates exist, otherwise
it will throw an exception.
PDF brought to you by
generated on April 16, 2014
Chapter 19: include | 81
Listing 20-1
Listing 20-2
Listing 20-3
Chapter 20
macro
Macros are comparable with functions in regular programming languages. They are useful to put often
used HTML idioms into reusable elements to not repeat yourself.
Here is a small example of a macro that renders a form element:
1
2
3
{% macro input(name, value, type, size) %}
<input type="{{ type|default('text') }}" name="{{ name }}" value="{{ value|e }}"
size="{{ size|default(20) }}" />
{% endmacro %}
Macros differs from native PHP functions in a few ways:
Default argument values are defined by using the default filter in the macro body;
Arguments of a macro are always optional.
But as with PHP functions, macros don't have access to the current template variables.
You can pass the whole context as an argument by using the special _context variable.
Macros can be defined in any template, and need to be "imported" before being used (see the
documentation for the import tag for more information):
1 {% import "forms.html" as forms %}
The above import call imports the "forms.html" file (which can contain only macros, or a template and
some macros), and import the functions as items of the forms variable.
The macro can then be called at will:
1
2
<p>{{ forms.input('username') }}</p>
<p>{{ forms.input('password', null, 'password') }}</p>
PDF brought to you by
generated on April 16, 2014
Chapter 20: macro | 82
Listing 20-4
Listing 20-5
If macros are defined and used in the same template, you can use the special _self variable to import
them:
1
2
3
{% import _self as forms %}
<p>{{ forms.input('username') }}</p>
When you define a macro in the template where you are going to use it, you might be tempted to
call the macro directly via _self.input() instead of importing it; even if seems to work, this is just
a side-effect of the current implementation and it won't work anymore in Twig 2.x.
When you want to use a macro in another macro from the same file, you need to import it locally:
1
2
3
4
5
6
7
8
9
10
11
{% macro input(name, value, type, size) %}
<input type="{{ type|default('text') }}" name="{{ name }}" value="{{ value|e }}"
size="{{ size|default(20) }}" />
{% endmacro %}
{% macro wrapped_input(name, value, type, size) %}
{% import _self as forms %}
<div class="field">
{{ forms.input(name, value, type, size) }}
</div>
{% endmacro %}
from, import
PDF brought to you by
generated on April 16, 2014
Chapter 20: macro | 83
Listing 21-1
Listing 21-2
Chapter 21
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:
1
2
3
{% sandbox %}
{% include 'user.html' %}
{% endsandbox %}
The sandbox tag is only available when the sandbox extension is enabled (see the Twig for
Developers chapter).
The sandbox tag can only be used to sandbox an include tag and it cannot be used to sandbox a
section of a template. The following example won't work:
1
2
3
4
5
{% sandbox %}
{% for i in 1..2 %}
{{ i }}
{% endfor %}
{% endsandbox %}
PDF brought to you by
generated on April 16, 2014
Chapter 21: sandbox | 84
Listing 22-1
Listing 22-2
Listing 22-3
Listing 22-4
Listing 22-5
Chapter 22
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:
1 {% set foo = 'bar' %}
After the set call, the foo variable is available in the template like any other ones:
1
2
{# displays bar #}
{{ foo }}
The assigned value can be any valid Twig expressions:
1
2
3
{% set foo = [1, 2] %}
{% set foo = {'foo': 'bar'} %}
{% set foo = 'foo' ~ 'bar' %}
Several variables can be assigned in one block:
1
2
3
4
5
6
{% set foo, bar = 'foo', 'bar' %}
{# is equivalent to #}
{% set foo = 'foo' %}
{% set bar = 'bar' %}
The set tag can also be used to 'capture' chunks of text:
1
2
3
{% set foo %}
<div id="pagination">
...
PDF brought to you by
generated on April 16, 2014
Chapter 22: set | 85
Listing 22-6
Listing 22-7
4
5
</div>
{% endset %}
If you enable automatic output escaping, Twig will only consider the content to be safe when
capturing chunks of text.
Note that loops are scoped in Twig; therefore a variable declared inside a for loop is not accessible
outside the loop itself:
1
2
3
4
5
{% for item in list %}
{% set foo = item %}
{% endfor %}
{# foo is NOT available #}
If you want to access the variable, just declare it before the loop:
1
2
3
4
5
6
{% set foo = "" %}
{% for item in list %}
{% set foo = item %}
{% endfor %}
{# foo is available #}
PDF brought to you by
generated on April 16, 2014
Chapter 22: set | 86
Listing 23-1
Chapter 23
spaceless
Use the spaceless tag to remove whitespace between HTML tags, not whitespace within HTML tags or
whitespace in plain text:
1
2
3
4
5
6
7
{% spaceless %}
<div>
<strong>foo</strong>
</div>
{% endspaceless %}
{# 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.
If you want to optimize the size of the generated HTML content, gzip compress the output instead.
If you want to create a tag that actually removes all extra whitespace in an HTML string, be warned
that this is not as easy as it seems to be (think of textarea or pre tags for instance). Using a third-
party library like Tidy is probably a better idea.
For more information on whitespace control, read the dedicated section of the documentation and
learn how you can also use the whitespace control modifier on your tags.
PDF brought to you by
generated on April 16, 2014
Chapter 23: spaceless | 87
Listing 24-1
Listing 24-2
Listing 24-3
Chapter 24
use
New in version 1.1: Horizontal reuse was added in Twig 1.1.
Horizontal reuse is an advanced Twig feature that is hardly ever needed in regular templates. It is
mainly used by projects that need to make template blocks reusable without using inheritance.
Template inheritance is one of the most powerful Twig's feature but it is limited to single inheritance;
a template can only extend one other template. This limitation makes template inheritance simple to
understand and easy to debug:
1
2
3
4
{% extends "base.html" %}
{% block title %}{% endblock %}
{% block content %}{% endblock %}
Horizontal reuse is a way to achieve the same goal as multiple inheritance, but without the associated
complexity:
1
2
3
4
5
6
{% 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):
1
2
# 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):
PDF brought to you by
generated on April 16, 2014
Chapter 24: use | 88
Listing 24-4
Listing 24-5
Listing 24-6
1
2
3
4
5
{% extends "base.html" %}
{% block sidebar %}{% endblock %}
{% block title %}{% endblock %}
{% block content %}{% endblock %}
The use tag only imports a template if it does not extend another template, if it does not define
macros, and if the body is empty. But it can use other templates.
Because use statements are resolved independently of the context passed to the template, the
template reference cannot be an expression.
The main template can also override any imported block. If the template already defines the sidebar
block, then the one defined in blocks.html is ignored. To avoid name conflicts, you can rename
imported blocks:
1
2
3
4
5
6
7
{% extends "base.html" %}
{% use "blocks.html" with sidebar as base_sidebar %}
{% block sidebar %}{% endblock %}
{% block title %}{% endblock %}
{% block content %}{% endblock %}
New in version 1.3: The parent() support was added in Twig 1.3.
The parent() function automatically determines the correct inheritance tree, so it can be used when
overriding a block defined in an imported template:
1
2
3
4
5
6
7
8
9
10
{% extends "base.html" %}
{% use "blocks.html" %}
{% block sidebar %}
{{ parent() }}
{% endblock %}
{% block title %}{% endblock %}
{% block content %}{% endblock %}
In this example, parent() will correctly call the sidebar block from the blocks.html template.
PDF brought to you by
generated on April 16, 2014
Chapter 24: use | 89
Listing 24-7
In Twig 1.2, renaming allows you to simulate inheritance by calling the "parent" block:
1
2
3
4
5
6
7
{% extends "base.html" %}
{% use "blocks.html" with sidebar as parent_sidebar %}
{% block sidebar %}
{{ block('parent_sidebar') }}
{% endblock %}
You can use as many use statements as you want in any given template. If two imported templates
define the same block, the latest one wins.
PDF brought to you by
generated on April 16, 2014
Chapter 24: use | 90
Listing 25-1
Chapter 25
verbatim
New in version 1.12: The verbatim tag was added in Twig 1.12 (it was named raw before).
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:
1
2
3
4
5
6
7
{% verbatim %}
<ul>
{% for item in seq %}
<li>{{ item }}</li>
{% endfor %}
</ul>
{% endverbatim %}
The verbatim tag works in the exact same way as the old raw tag, but was renamed to avoid
confusion with the raw filter.
PDF brought to you by
generated on April 16, 2014
Chapter 25: verbatim | 91
Listing 26-1
Chapter 26
abs
The abs filter returns the absolute value.
1
2
3
4
5
{# number = -5 #}
{{ number|abs }}
{# outputs 5 #}
Internally, Twig uses the PHP abs
1
function.
1. http://php.net/abs
PDF brought to you by
generated on April 16, 2014
Chapter 26: abs | 92
Listing 27-1
Listing 27-2
Chapter 27
batch
New in version 1.12.3: The batch filter was added in Twig 1.12.3.
The batch filter "batches" items by returning a list of lists with the given number of items. If you provide
a second parameter, it is used to fill missing items:
1
2
3
4
5
6
7
8
9
10
11
{% set items = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] %}
<table>
{% for row in items|batch(3, 'No item') %}
<tr>
{% for column in row %}
<td>{{ column }}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
The above example will be rendered as:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<table>
<tr>
<td>a</td>
<td>b</td>
<td>c</td>
</tr>
<tr>
<td>d</td>
<td>e</td>
<td>f</td>
</tr>
<tr>
<td>g</td>
<td>No item</td>
<td>No item</td>
</tr>
</table>
PDF brought to you by
generated on April 16, 2014
Chapter 27: batch | 93
Listing 28-1
Chapter 28
capitalize
The capitalize filter capitalizes a value. The first character will be uppercase, all others lowercase:
1
2
3
{{ 'my first car'|capitalize }}
{# outputs 'My first car' #}
PDF brought to you by
generated on April 16, 2014
Chapter 28: capitalize | 94
Listing 29-1
Chapter 29
convert_encoding
New in version 1.4: The convert_encoding filter was added in Twig 1.4.
The convert_encoding filter converts a string from one encoding to another. The first argument is the
expected output charset and the second one is the input charset:
1 {{ data|convert_encoding('UTF-8', 'iso-2022-jp') }}
This filter relies on the iconv
1
or mbstring
2
extension, so one of themmust be installed. In case both
are installed, mbstring
3
is used by default (Twig before 1.8.1 uses iconv
4
by default).
Arguments
from: The input charset
to: The output charset
1. http://php.net/iconv
2. http://php.net/mbstring
3. http://php.net/mbstring
4. http://php.net/iconv
PDF brought to you by
generated on April 16, 2014
Chapter 29: convert_encoding | 95
Listing 30-1
Listing 30-2
Listing 30-3
Listing 30-4
Chapter 30
date
New in version 1.1: The timezone support has been added in Twig 1.1.
New in version 1.5: The default date format support has been added in Twig 1.5.
New in version 1.6.1: The default timezone support has been added in Twig 1.6.1.
Newin version 1.11.0: The introduction of the false value for the timezone was introduced in Twig 1.11.0
The date filter formats a date to a given format:
1 {{ post.published_at|date("m/d/Y") }}
The format specifier is the same as supported by date
1
, except when the filtered data is of type
DateInterval
2
, when the format must conform to DateInterval::format
3
instead.
The date filter accepts strings (it must be in a format supported by the strtotime
4
function), DateTime
5
instances, or DateInterval
6
instances. For instance, to display the current date, filter the word "now":
1 {{ "now"|date("m/d/Y") }}
To escape words and characters in the date format use \\ in front of each character:
1 {{ post.published_at|date("F jS \\a\\t g:ia") }}
If the value passed to the date filter is null, it will return the current date by default. If an empty string
is desired instead of the current date, use a ternary operator:
{{ post.published_at is empty ? "" : post.published_at|date("m/d/Y") }}
1. http://www.php.net/date
2. http://www.php.net/DateInterval
3. http://www.php.net/DateInterval.format
4. http://www.php.net/strtotime
5. http://www.php.net/DateTime
6. http://www.php.net/DateInterval
PDF brought to you by
generated on April 16, 2014
Chapter 30: date | 96
Listing 30-5
Listing 30-6
Listing 30-7
Listing 30-8
If no format is provided, Twig will use the default one: F j, Y H:i. This default can be easily changed by
calling the setDateFormat() method on the core extension instance. The first argument is the default
format for dates and the second one is the default format for date intervals:
1
2
$twig = new Twig_Environment($loader);
$twig->getExtension('core')->setDateFormat('d/m/Y', '%d days');
Timezone
By default, the date is displayed by applying the default timezone (the one specified in php.ini or declared
in Twig -- see below), but you can override it by explicitly specifying a timezone:
1 {{ post.published_at|date("m/d/Y", "Europe/Paris") }}
If the date is already a DateTime object, and if you want to keep its current timezone, pass false as the
timezone value:
1 {{ post.published_at|date("m/d/Y", false) }}
The default timezone can also be set globally by calling setTimezone():
1
2
$twig = new Twig_Environment($loader);
$twig->getExtension('core')->setTimezone('Europe/Paris');
Arguments
format: The date format
timezone: The date timezone
PDF brought to you by
generated on April 16, 2014
Chapter 30: date | 97
Listing 31-1
Chapter 31
date_modify
New in version 1.9.0: The date_modify filter has been added in Twig 1.9.0.
The date_modify filter modifies a date with a given modifier string:
1 {{ 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
1
function) or
DateTime
2
instances. You can easily combine it with the date filter for formatting.
Arguments
modifier: The modifier
1. http://www.php.net/strtotime
2. http://www.php.net/DateTime
PDF brought to you by
generated on April 16, 2014
Chapter 31: date_modify | 98
Listing 32-1
Listing 32-2
Chapter 32
default
The default filter returns the passed default value if the value is undefined or empty, otherwise the value
of the variable:
1
2
3
4
5
6
7
{{ var|default('var is not defined') }}
{{ var.foo|default('foo item on var is not defined') }}
{{ var['foo']|default('foo item on var is not defined') }}
{{ ''|default('passed var is empty') }}
When using the default filter on an expression that uses variables in some method calls, be sure to use
the default filter whenever a variable can be undefined:
1 {{ var.method(foo|default('foo'))|default('foo') }}
Read the documentation for the defined and empty tests to learn more about their semantics.
Arguments
default: The default value
PDF brought to you by
generated on April 16, 2014
Chapter 32: default | 99
Listing 33-1
Listing 33-2
Listing 33-3
Listing 33-4
Chapter 33
escape
New in version 1.9.0: The css, url, and html_attr strategies were added in Twig 1.9.0.
New in version 1.14.0: The ability to define custom escapers was added in Twig 1.14.0.
The escape filter escapes a string for safe insertion into the final output. It supports different escaping
strategies depending on the template context.
By default, it uses the HTML escaping strategy:
1 {{ user.username|escape }}
For convenience, the e filter is defined as an alias:
1 {{ user.username|e }}
The escape filter can also be used in other contexts than HTML thanks to an optional argument which
defines the escaping strategy to use:
1
2
3
{{ user.username|e }}
{# is equivalent to #}
{{ user.username|e('html') }}
And here is how to escape variables included in JavaScript code:
1
2
{{ user.username|escape('js') }}
{{ user.username|e('js') }}
The escape filter supports the following escaping strategies:
html: escapes a string for the HTML body context.
js: escapes a string for the JavaScript context.
css: escapes a string for the CSS context. CSS escaping can be applied to any string being
inserted into CSS and escapes everything except alphanumerics.
url: escapes a string for the URI or parameter contexts. This should not be used to escape
an entire URI; only a subcomponent being inserted.
PDF brought to you by
generated on April 16, 2014
Chapter 33: escape | 100
Listing 33-5
Listing 33-6
Listing 33-7
html_attr: escapes a string for the HTML attribute context.
Internally, escape uses the PHP native htmlspecialchars
1
function for the HTML escaping strategy.
When using automatic escaping, Twig tries to not double-escape a variable when the automatic
escaping strategy is the same as the one applied by the escape filter; but that does not work when
using a variable as the escaping strategy:
1
2
3
4
5
6
{% set strategy = 'html' %}
{% autoescape 'html' %}
{{ var|escape('html') }} {# won't be double-escaped #}
{{ var|escape(strategy) }} {# will be double-escaped #}
{% endautoescape %}
When using a variable as the escaping strategy, you should disable automatic escaping:
1
2
3
4
5
{% set strategy = 'html' %}
{% autoescape 'html' %}
{{ var|escape(strategy)|raw }} {# won't be double-escaped #}
{% endautoescape %}
Custom Escapers
You can define custom escapers by calling the setEscaper() method on the core extension instance.
The first argument is the escaper name (to be used in the escape call) and the second one must be a valid
PHP callable:
1
2
$twig = new Twig_Environment($loader);
$twig->getExtension('core')->setEscaper('csv', 'csv_escaper'));
When called by Twig, the callable receives the Twig environment instance, the string to escape, and the
charset.
Built-in escapers cannot be overridden mainly they should be considered as the final
implementation and also for better performance.
Arguments
strategy: The escaping strategy
charset: The string charset
1. http://php.net/htmlspecialchars
PDF brought to you by
generated on April 16, 2014
Chapter 33: escape | 101
Listing 34-1
Chapter 34
first
New in version 1.12.2: The first filter was added in Twig 1.12.2.
The first filter returns the first "element" of a sequence, a mapping, or a string:
1
2
3
4
5
6
7
8
{{ [1, 2, 3, 4]|first }}
{# outputs 1 #}
{{ { a: 1, b: 2, c: 3, d: 4 }|first }}
{# outputs 1 #}
{{ '1234'|first }}
{# outputs 1 #}
It also works with objects implementing the Traversable
1
interface.
1. http://php.net/manual/en/class.traversable.php
PDF brought to you by
generated on April 16, 2014
Chapter 34: first | 102
Listing 35-1
Chapter 35
format
The format filter formats a given string by replacing the placeholders (placeholders follows the sprintf
1
notation):
1
2
3
4
{{ "I like %s and %s."|format(foo, "bar") }}
{# outputs I like foo and bar
if the foo parameter equals to the foo string. #}
replace
1. http://www.php.net/sprintf
PDF brought to you by
generated on April 16, 2014
Chapter 35: format | 103
Listing 36-1
Listing 36-2
Chapter 36
join
The join filter returns a string which is the concatenation of the items of a sequence:
1
2
{{ [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
{{ [1, 2, 3]|join('|') }}
{# outputs 1|2|3 #}
Arguments
glue: The separator
PDF brought to you by
generated on April 16, 2014
Chapter 36: join | 104
Listing 37-1
Chapter 37
json_encode
The json_encode filter returns the JSON representation of a string:
1 {{ data|json_encode() }}
Internally, Twig uses the PHP json_encode
1
function.
Arguments
options: A bitmask of json_encode options
2
({{
data|json_encode(constant('JSON_PRETTY_PRINT')) }})
1. http://php.net/json_encode
2. http://www.php.net/manual/en/json.constants.php
PDF brought to you by
generated on April 16, 2014
Chapter 37: json_encode | 105
Listing 38-1
Chapter 38
keys
The keys filter returns the keys of an array. It is useful when you want to iterate over the keys of an array:
1
2
3
{% for key in array|keys %}
...
{% endfor %}
PDF brought to you by
generated on April 16, 2014
Chapter 38: keys | 106
Listing 39-1
Chapter 39
last
New in version 1.12.2: The last filter was added in Twig 1.12.2.
The last filter returns the last "element" of a sequence, a mapping, or a string:
1
2
3
4
5
6
7
8
{{ [1, 2, 3, 4]|last }}
{# outputs 4 #}
{{ { a: 1, b: 2, c: 3, d: 4 }|last }}
{# outputs 4 #}
{{ '1234'|last }}
{# outputs 4 #}
It also works with objects implementing the Traversable
1
interface.
1. http://php.net/manual/en/class.traversable.php
PDF brought to you by
generated on April 16, 2014
Chapter 39: last | 107
Listing 40-1
Chapter 40
length
The length filters returns the number of items of a sequence or mapping, or the length of a string:
1
2
3
{% if users|length > 10 %}
...
{% endif %}
PDF brought to you by
generated on April 16, 2014
Chapter 40: length | 108
Listing 41-1
Chapter 41
lower
The lower filter converts a value to lowercase:
1
2
3
{{ 'WELCOME'|lower }}
{# outputs 'welcome' #}
PDF brought to you by
generated on April 16, 2014
Chapter 41: lower | 109
Listing 42-1
Chapter 42
nl2br
New in version 1.5: The nl2br filter was added in Twig 1.5.
The nl2br filter inserts HTML line breaks before all newlines in a string:
1
2
3
4
5
6
7
{{ "I like Twig.\nYou will like it too."|nl2br }}
{# outputs
I like Twig.<br />
You will like it too.
#}
The nl2br filter pre-escapes the input before applying the transformation.
PDF brought to you by
generated on April 16, 2014
Chapter 42: nl2br | 110
Listing 43-1
Listing 43-2
Listing 43-3
Chapter 43
number_format
New in version 1.5: The number_format filter was added in Twig 1.5
The number_format filter formats numbers. It is a wrapper around PHP's number_format
1
function:
1 {{ 200.35|number_format }}
You can control the number of decimal places, decimal point, and thousands separator using the
additional arguments:
1 {{ 9800.333|number_format(2, '.', ',') }}
If no formatting options are provided then Twig will use the default formatting options of:
0 decimal places.
. as the decimal point.
, as the thousands separator.
These defaults can be easily changed through the core extension:
1
2
$twig = new Twig_Environment($loader);
$twig->getExtension('core')->setNumberFormat(3, '.', ',');
The defaults set for number_format can be over-ridden upon each call using the additional parameters.
Arguments
decimal: The number of decimal points to display
decimal_point: The character(s) to use for the decimal point
thousand_sep: The character(s) to use for the thousands separator
1. http://php.net/number_format
PDF brought to you by
generated on April 16, 2014
Chapter 43: number_format | 111
Listing 44-1
Listing 44-2
Listing 44-3
Chapter 44
merge
The merge filter merges an array with another array:
1
2
3
4
5
{% 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:
1
2
3
4
5
{% 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.
If you want to ensure that some values are defined in an array (by given default values), reverse the
two elements in the call:
1
2
3
4
5
{% set items = { 'apple': 'fruit', 'orange': 'fruit' } %}
{% set items = { 'apple': 'unknown' }|merge(items) %}
{# items now contains { 'apple': 'fruit', 'orange': 'fruit' } #}
PDF brought to you by
generated on April 16, 2014
Chapter 44: merge | 112
Listing 45-1
Chapter 45
upper
The upper filter converts a value to uppercase:
1
2
3
{{ 'welcome'|upper }}
{# outputs 'WELCOME' #}
PDF brought to you by
generated on April 16, 2014
Chapter 45: upper | 113
Listing 46-1
Chapter 46
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:
1
2
3
{% autoescape %}
{{ var|raw }} {# var won't be escaped #}
{% endautoescape %}
PDF brought to you by
generated on April 16, 2014
Chapter 46: raw | 114
Listing 47-1
Chapter 47
replace
The replace filter formats a given string by replacing the placeholders (placeholders are free-form):
1
2
3
4
{{ "I like %this% and %that%."|replace({'%this%': foo, '%that%': "bar"}) }}
{# outputs I like foo and bar
if the foo parameter equals to the foo string. #}
Arguments
replace_pairs: The placeholder values
format
PDF brought to you by
generated on April 16, 2014
Chapter 47: replace | 115
Listing 48-1
Listing 48-2
Chapter 48
reverse
New in version 1.6: Support for strings has been added in Twig 1.6.
The reverse filter reverses a sequence, a mapping, or a string:
1
2
3
4
5
6
7
{% for user in users|reverse %}
...
{% endfor %}
{{ '1234'|reverse }}
{# outputs 4321 #}
For sequences and mappings, numeric keys are not preserved. To reverse them as well, pass true
as an argument to the reverse filter:
1
2
3
4
5
6
7
8
9
10
11
{% for key, value in {1: "a", 2: "b", 3: "c"}|reverse %}
{{ key }}: {{ value }}
{%- endfor %}
{# output: 0: c 1: b 2: a #}
{% for key, value in {1: "a", 2: "b", 3: "c"}|reverse(true) %}
{{ key }}: {{ value }}
{%- endfor %}
{# output: 3: c 2: b 1: a #}
It also works with objects implementing the Traversable
1
interface.
1. http://php.net/Traversable
PDF brought to you by
generated on April 16, 2014
Chapter 48: reverse | 116
Arguments
preserve_keys: Preserve keys when reversing a mapping or a sequence.
PDF brought to you by
generated on April 16, 2014
Chapter 48: reverse | 117
Listing 49-1
Chapter 49
round
New in version 1.15.0: The round filter was added in Twig 1.15.0.
The round filter rounds a number to a given precision:
1
2
3
4
5
{{ 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.
The // operator is equivalent to |round(0, 'floor').
Arguments
precision: The rounding precision
method: The rounding method
PDF brought to you by
generated on April 16, 2014
Chapter 49: round | 118
Listing 50-1
Listing 50-2
Listing 50-3
Chapter 50
slice
New in version 1.6: The slice filter was added in Twig 1.6.
The slice filter extracts a slice of a sequence, a mapping, or a string:
1
2
3
4
5
6
7
{% for i in [1, 2, 3, 4, 5]|slice(1, 2) %}
{# will iterate over 2 and 3 #}
{% endfor %}
{{ '12345'|slice(1, 2) }}
{# outputs 23 #}
You can use any valid expression for both the start and the length:
1
2
3
{% for i in [1, 2, 3, 4, 5]|slice(start, length) %}
{# ... #}
{% endfor %}
As syntactic sugar, you can also use the [] notation:
1
2
3
4
5
6
7
8
9
10
11
{% for i in [1, 2, 3, 4, 5][start:length] %}
{# ... #}
{% endfor %}
{{ '12345'[1:2] }}
{# you can omit the first argument -- which is the same as 0 #}
{{ '12345'[:2] }} {# will display "12" #}
{# you can omit the last argument -- which will select everything till the end #}
{{ '12345'[2:] }} {# will display "345" #}
The slice filter works as the array_slice
1
PHP function for arrays and substr
2
for strings.
1. http://php.net/array_slice
2. http://php.net/substr
PDF brought to you by
generated on April 16, 2014
Chapter 50: slice | 119
If the start is non-negative, the sequence will start at that start in the variable. If start is negative, the
sequence will start that far from the end of the variable.
If length is given and is positive, then the sequence will have up to that many elements in it. If the variable
is shorter than the length, then only the available variable elements will be present. If length is given and
is negative then the sequence will stop that many elements from the end of the variable. If it is omitted,
then the sequence will have everything from offset up until the end of the variable.
It also works with objects implementing the Traversable
3
interface.
Arguments
start: The start of the slice
length: The size of the slice
preserve_keys: Whether to preserve key or not (when the input is an array)
3. http://php.net/manual/en/class.traversable.php
PDF brought to you by
generated on April 16, 2014
Chapter 50: slice | 120
Listing 51-1
Chapter 51
sort
The sort filter sorts an array:
1
2
3
{% for user in users|sort %}
...
{% endfor %}
Internally, Twig uses the PHP asort
1
function to maintain index association.
1. http://php.net/asort
PDF brought to you by
generated on April 16, 2014
Chapter 51: sort | 121
Listing 52-1
Listing 52-2
Listing 52-3
Chapter 52
split
New in version 1.10.3: The split filter was added in Twig 1.10.3.
The split filter splits a string by the given delimiter and returns a list of strings:
1
2
{{ "one,two,three"|split(',') }}
{# returns ['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.
1
2
{{ "one,two,three,four,five"|split(',', 3) }}
{# returns ['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).
1
2
3
4
5
{{ "123"|split('') }}
{# returns ['1', '2', '3'] #}
{{ "aabbcc"|split('', 2) }}
{# returns ['aa', 'bb', 'cc'] #}
Internally, Twig uses the PHP explode
1
or str_split
2
(if delimiter is empty) functions for string
splitting.
PDF brought to you by
generated on April 16, 2014
Chapter 52: split | 122
Arguments
delimiter: The delimiter
limit: The limit argument
1. http://php.net/explode
2. http://php.net/str_split
PDF brought to you by
generated on April 16, 2014
Chapter 52: split | 123
Listing 53-1
Chapter 53
striptags
The striptags filter strips SGML/XML tags and replace adjacent whitespace by one space:
1 {{ some_html|striptags }}
Internally, Twig uses the PHP strip_tags
1
function.
1. http://php.net/strip_tags
PDF brought to you by
generated on April 16, 2014
Chapter 53: striptags | 124
Listing 54-1
Chapter 54
title
The title filter returns a titlecased version of the value. Words will start with uppercase letters, all
remaining characters are lowercase:
1
2
3
{{ 'my first car'|title }}
{# outputs 'My First Car' #}
PDF brought to you by
generated on April 16, 2014
Chapter 54: title | 125
Listing 55-1
Chapter 55
trim
New in version 1.6.2: The trim filter was added in Twig 1.6.2.
The trim filter strips whitespace (or other characters) from the beginning and end of a string:
1
2
3
4
5
6
7
{{ ' I like Twig. '|trim }}
{# outputs 'I like Twig.' #}
{{ ' I like Twig.'|trim('.') }}
{# outputs ' I like Twig' #}
Internally, Twig uses the PHP trim
1
function.
Arguments
character_mask: The characters to strip
1. http://php.net/trim
PDF brought to you by
generated on April 16, 2014
Chapter 55: trim | 126
Listing 56-1
Chapter 56
url_encode
New in version 1.12.3: Support for encoding an array as query string was added in Twig 1.12.3.
The url_encode filter percent encodes a given string as URL segment or an array as query string:
1
2
3
4
5
6
7
8
{{ "path-seg*ment"|url_encode }}
{# outputs "path-seg%2Ament" #}
{{ "string with spaces"|url_encode(true) }}
{# outputs "string%20with%20spaces" #}
{{ {'param': 'value', 'foo': 'bar'}|url_encode }}
{# outputs "param=value&foo=bar" #}
Internally, Twig uses the PHP urlencode
1
(or rawurlencode
2
if you pass true as the first parameter)
or the http_build_query
3
function.
1. http://php.net/urlencode
2. http://php.net/rawurlencode
3. http://php.net/http_build_query
PDF brought to you by
generated on April 16, 2014
Chapter 56: url_encode | 127
Listing 57-1
Listing 57-2
Chapter 57
attribute
New in version 1.2: The attribute function was added in Twig 1.2.
The attribute function can be used to access a "dynamic" attribute of a variable:
1
2
3
{{ 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' }}
The resolution algorithm is the same as the one used for the . notation, except that the item can
be any valid expression.
PDF brought to you by
generated on April 16, 2014
Chapter 57: attribute | 128
Listing 58-1
Chapter 58
block
When a template uses inheritance and if you want to print a block multiple times, use the block function:
1
2
3
4
5
<title>{% block title %}{% endblock %}</title>
<h1>{{ block('title') }}</h1>
{% block body %}{% endblock %}
extends, parent
PDF brought to you by
generated on April 16, 2014
Chapter 58: block | 129
Listing 59-1
Listing 59-2
Chapter 59
constant
constant returns the constant value for a given string:
1
2
{{ some_date|date(constant('DATE_W3C')) }}
{{ constant('Namespace\\Classname::CONSTANT_NAME') }}
As of 1.12.1 you can read constants from object instances as well:
1 {{ constant('RSS', date) }}
PDF brought to you by
generated on April 16, 2014
Chapter 59: constant | 130
Listing 60-1
Listing 60-2
Chapter 60
cycle
The cycle function cycles on an array of values:
1
2
3
4
5
6
{% 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 %}
The array can contain any number of values:
1
2
3
4
5
{% set fruits = ['apple', 'orange', 'citrus'] %}
{% for i in 0..10 %}
{{ cycle(fruits, i) }}
{% endfor %}
Arguments
position: The cycle position
PDF brought to you by
generated on April 16, 2014
Chapter 60: cycle | 131
Listing 61-1
Listing 61-2
Listing 61-3
Listing 61-4
Chapter 61
date
New in version 1.6: The date function has been added in Twig 1.6.
New in version 1.6.1: The default timezone support has been added in Twig 1.6.1.
Converts an argument to a date to allow date comparison:
1
2
3
{% if date(user.created_at) < date('-2days') %}
{# do something #}
{% endif %}
The argument must be in a format supported by the date
1
function.
You can pass a timezone as the second argument:
1
2
3
{% if date(user.created_at) < date('-2days', 'Europe/Paris') %}
{# do something #}
{% endif %}
If no argument is passed, the function returns the current date:
1
2
3
{% if date(user.created_at) < date() %}
{# always! #}
{% endif %}
You can set the default timezone globally by calling setTimezone() on the core extension
instance:
1
2
$twig = new Twig_Environment($loader);
$twig->getExtension('core')->setTimezone('Europe/Paris');
1. http://www.php.net/date
PDF brought to you by
generated on April 16, 2014
Chapter 61: date | 132
Arguments
date: The date
timezone: The timezone
PDF brought to you by
generated on April 16, 2014
Chapter 61: date | 133
Listing 62-1
Listing 62-2
Listing 62-3
Chapter 62
dump
New in version 1.5: The dump function was added in Twig 1.5.
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:
1 {{ dump(user) }}
The dump function is not available by default. You must add the Twig_Extension_Debug extension
explicitly when creating your Twig environment:
1
2
3
4
5
$twig = new Twig_Environment($loader, array(
'debug' => true,
// ...
));
$twig->addExtension(new Twig_Extension_Debug());
Even when enabled, the dump function won't display anything if the debug option on the
environment is not enabled (to avoid leaking debug information on a production server).
In an HTML context, wrap the output with a pre tag to make it easier to read:
1
2
3
<pre>
{{ dump(user) }}
</pre>
Using a pre tag is not needed when XDebug
1
is enabled and html_errors is on; as a bonus, the
output is also nicer with XDebug enabled.
You can debug several variables by passing them as additional arguments:
1. http://xdebug.org/docs/display
PDF brought to you by
generated on April 16, 2014
Chapter 62: dump | 134
Listing 62-4
Listing 62-5
1 {{ dump(user, categories) }}
If you don't pass any value, all variables from the current context are dumped:
1 {{ dump() }}
Internally, Twig uses the PHP var_dump
2
function.
Arguments
context: The context to dump
2. http://php.net/var_dump
PDF brought to you by
generated on April 16, 2014
Chapter 62: dump | 135
Listing 63-1
Listing 63-2
Listing 63-3
Listing 63-4
Listing 63-5
Chapter 63
include
New in version 1.12: The include function was added in Twig 1.12.
The include function returns the rendered content of a template:
1
2
{{ include('template.html') }}
{{ include(some_var) }}
Included templates have access to the variables of the active context.
If you are using the filesystem loader, the templates are looked for in the paths defined by it.
The context is passed by default to the template but you can also pass additional variables:
1
2
{# template.html will have access to the variables from the current context and the
additional ones provided #}
{{ include('template.html', {foo: 'bar'}) }}
You can disable access to the context by setting with_context to false:
1
2
{# only the foo variable will be accessible #}
{{ include('template.html', {foo: 'bar'}, with_context = false) }}
1
2
{# no variables will be accessible #}
{{ include('template.html', with_context = false) }}
And if the expression evaluates to a Twig_Template object, Twig will use it directly:
1
2
3
4
5
// {{ include(template) }}
$template = $twig->loadTemplate('some_template.twig');
$twig->loadTemplate('template.twig')->display(array('template' => $template));
When you set the ignore_missing flag, Twig will return an empty string if the template does not exist:
PDF brought to you by
generated on April 16, 2014
Chapter 63: include | 136
Listing 63-6
Listing 63-7
Listing 63-8
1 {{ include('sidebar.html', ignore_missing = true) }}
You can also provide a list of templates that are checked for existence before inclusion. The first template
that exists will be rendered:
1 {{ include(['page_detailed.html', 'page.html']) }}
If ignore_missing is set, it will fall back to rendering nothing if none of the templates exist, otherwise it
will throw an exception.
When including a template created by an end user, you should consider sandboxing it:
1 {{ include('page.html', sandboxed = true) }}
Arguments
template: The template to render
variables: The variables to pass to the template
with_context: Whether to pass the current context variables or not
ignore_missing: Whether to ignore missing templates or not
sandboxed: Whether to sandbox the template or not
PDF brought to you by
generated on April 16, 2014
Chapter 63: include | 137
Listing 64-1
Listing 64-2
Chapter 64
max
New in version 1.15: The max function was added in Twig 1.15.
max returns the biggest value of a sequence or a set of values:
1
2
{{ max(1, 3, 2) }}
{{ max([1, 3, 2]) }}
When called with a mapping, max ignores keys and only compares values:
1
2
{{ max({2: "two", 1: "one", 3: "three", 5: "five", 4: "for"}) }}
{# return "two" #}
PDF brought to you by
generated on April 16, 2014
Chapter 64: max | 138
Listing 65-1
Listing 65-2
Chapter 65
min
New in version 1.15: The min function was added in Twig 1.15.
min returns the lowest value of a sequence or a set of values:
1
2
{{ min(1, 3, 2) }}
{{ min([1, 3, 2]) }}
When called with a mapping, min ignores keys and only compares values:
1
2
{{ min({2: "two", 1: "one", 3: "three", 5: "five", 4: "for"}) }}
{# return "five" #}
PDF brought to you by
generated on April 16, 2014
Chapter 65: min | 139
Listing 66-1
Chapter 66
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:
1
2
3
4
5
6
7
{% 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.
extends, block, block
PDF brought to you by
generated on April 16, 2014
Chapter 66: parent | 140
Listing 67-1
Chapter 67
random
New in version 1.5: The random function was added in Twig 1.5.
New in version 1.6: String and integer handling was added in Twig 1.6.
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).
1
2
3
4
{{ 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 #}
Arguments
values: The values
PDF brought to you by
generated on April 16, 2014
Chapter 67: random | 141
Listing 68-1
Listing 68-2
Listing 68-3
Chapter 68
range
Returns a list containing an arithmetic progression of integers:
1
2
3
4
5
{% 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):
1
2
3
4
5
{% 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):
1
2
3
{% for i in 0..3 %}
{{ i }},
{% endfor %}
The range function works as the native PHP range
1
function.
Arguments
low: The first value of the sequence.
1. http://php.net/range
PDF brought to you by
generated on April 16, 2014
Chapter 68: range | 142
high: The highest possible value of the sequence.
step: The increment between elements of the sequence.
PDF brought to you by
generated on April 16, 2014
Chapter 68: range | 143
Listing 69-1
Chapter 69
source
New in version 1.15: The source function was added in Twig 1.15.
The source function returns the content of a template without rendering it:
1
2
{{ source('template.html') }}
{{ source(some_var) }}
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.
Arguments
name: The name of the template to read
PDF brought to you by
generated on April 16, 2014
Chapter 69: source | 144
Listing 70-1
Listing 70-2
Chapter 70
template_from_string
New in version 1.11: The template_from_string function was added in Twig 1.11.
The template_from_string function loads a template from a string:
1
2
{{ include(template_from_string("Hello {{ name }}")) }}
{{ include(template_from_string(page.template)) }}
The template_from_string function is not available by default. You must add the
Twig_Extension_StringLoader extension explicitly when creating your Twig environment:
1
2
$twig = new Twig_Environment(...);
$twig->addExtension(new Twig_Extension_StringLoader());
Even if you will probably always use the template_from_string function with the include
function, you can use it with any tag or function that takes a template as an argument (like the
embed or extends tags).
Arguments
template: The template
PDF brought to you by
generated on April 16, 2014
Chapter 70: template_from_string | 145
Listing 71-1
Listing 71-2
Chapter 71
constant
constant checks if a variable has the exact same value as a constant. You can use either global constants
or class constants:
1
2
3
{% 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:
1
2
3
{% if post.status is constant('PUBLISHED', post) %}
the status attribute is exactly the same as Post::PUBLISHED
{% endif %}
PDF brought to you by
generated on April 16, 2014
Chapter 71: constant | 146
Listing 72-1
Listing 72-2
Chapter 72
defined
defined checks if a variable is defined in the current context. This is very useful if you use the
strict_variables option:
1
2
3
4
5
6
7
8
9
10
11
12
13
{# 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:
1
2
3
{% if var is defined and foo.method(var) is defined %}
...
{% endif %}
PDF brought to you by
generated on April 16, 2014
Chapter 72: defined | 147
Listing 73-1
Chapter 73
divisible by
New in version 1.14.2: The divisible by test was added in Twig 1.14.2 as an alias for divisibleby.
divisible by checks if a variable is divisible by a number:
1
2
3
{% if loop.index is divisible by(3) %}
...
{% endif %}
PDF brought to you by
generated on April 16, 2014
Chapter 73: divisible by | 148
Listing 74-1
Chapter 74
empty
empty checks if a variable is empty:
1
2
3
4
{# evaluates to true if the foo variable is null, false, an empty array, or the empty
string #}
{% if foo is empty %}
...
{% endif %}
PDF brought to you by
generated on April 16, 2014
Chapter 74: empty | 149
Listing 75-1
Chapter 75
even
even returns true if the given number is even:
1 {{ var is even }}
odd
PDF brought to you by
generated on April 16, 2014
Chapter 75: even | 150
Listing 76-1
Chapter 76
iterable
New in version 1.7: The iterable test was added in Twig 1.7.
iterable checks if a variable is an array or a traversable object:
1
2
3
4
5
6
7
8
9
{# 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 %}
PDF brought to you by
generated on April 16, 2014
Chapter 76: iterable | 151
Listing 77-1
Chapter 77
null
null returns true if the variable is null:
1 {{ var is null }}
none is an alias for null.
PDF brought to you by
generated on April 16, 2014
Chapter 77: null | 152
Listing 78-1
Chapter 78
odd
odd returns true if the given number is odd:
1 {{ var is odd }}
even
PDF brought to you by
generated on April 16, 2014
Chapter 78: odd | 153
Listing 79-1
Chapter 79
same as
New in version 1.14.2: The same as test was added in Twig 1.14.2 as an alias for sameas.
same as checks if a variable points to the same memory address than another variable:
1
2
3
{% if foo.attribute is same as(false) %}
the foo attribute really is the 'false' PHP value
{% endif %}
PDF brought to you by
generated on April 16, 2014
Chapter 79: same as | 154
Listing 80-1
Listing 80-2
Listing 80-3
Chapter 80
Installation
You have multiple ways to install Twig.
Installing the Twig PHP package
Installing via Composer (recommended)
1. Install Composer in your project:
1 curl -s http://getcomposer.org/installer | php
2. Create a composer.json file in your project root:
1
2
3
4
5
{
"require": {
"twig/twig": "1.*"
}
}
3. Install via Composer
1 php composer.phar install
If you want to learn more about Composer, the composer.json file syntax and its usage, you can
read the online documentation
1
.
Installing from the tarball release
1. Download the most recent tarball from the download page
2
1. http://getcomposer.org/doc
PDF brought to you by
generated on April 16, 2014
Chapter 80: Installation | 155
Listing 80-4
Listing 80-5
2. Unpack the tarball
3. Move the files somewhere in your project
Installing the development version
1. Install Git
2. git clone git://github.com/fabpot/Twig.git
Installing the PEAR package
1. Install PEAR
2. pear channel-discover pear.twig-project.org
3. pear install twig/Twig (or pear install twig/Twig-beta)
Installing the C extension
New in version 1.4: The C extension was added in Twig 1.4.
Twig comes with a C extension that enhances the performance of the Twig runtime engine.
You can install it via PEAR:
1. Install PEAR
2. pear channel-discover pear.twig-project.org
3. pear install twig/CTwig (or pear install twig/CTwig-beta)
Or manually like any other PHP extension:
1
2
3
4
5
$ cd ext/twig
$ phpize
$ ./configure
$ make
$ make install
For Windows:
1. Setup the build environment following the PHP documentation
3
2. Put Twig's C extension source code into C:\php-sdk\phpdev\vcXX\x86\php-source-
directory\ext\twig
3. Use the configure --disable-all --enable-cli --enable-twig=shared command instead
of step 14
4. nmake
5. Copy the C:\php-sdk\phpdev\vcXX\x86\php-source-
directory\Release_TS\php_twig.dll file to your PHP setup.
For Windows ZendServer, TS is not enabled as mentionned in Zend Server FAQ.
You have to use configure --disable-all --disable-zts --enable-cli --enable-twig=shared to be able to
build the twig C extension for ZendServer.
The built DLL will be available in C:\php-sdk\phpdev\vcXX\x86\php-source-directory\Release
Finally, enable the extension in your php.ini configuration file:
2. https://github.com/fabpot/Twig/tags
3. https://wiki.php.net/internals/windows/stepbystepbuild
PDF brought to you by
generated on April 16, 2014
Chapter 80: Installation | 156
1
2
extension=twig.so #For Unix systems
extension=php_twig.dll #For Windows systems
And fromnow on, Twig will automatically compile your templates to take advantage of the C extension.
Note that this extension does not replace the PHP code but only provides an optimized version of the
Twig_Template::getAttribute() method.
PDF brought to you by
generated on April 16, 2014
Chapter 80: Installation | 157
Chapter 81
Deprecated Features
This document lists all deprecated features in Twig. Deprecated features are kept for backward
compatibility and removed in the next major release (a feature that was deprecated in Twig 1.x is
removed in Twig 2.0).
Token Parsers
As of Twig 1.x, the token parser broker sub-system is deprecated. The following class and
interface will be removed in 2.0:
Twig_TokenParserBrokerInterface
Twig_TokenParserBroker
Extensions
As of Twig 1.x, the ability to remove an extension is deprecated and the
Twig_Environment::removeExtension() method will be removed in 2.0.
PEAR
PEAR support will be discontinued in Twig 2.0, and no PEAR packages will be provided. Use Composer
instead.
Filters
As of Twig 1.x, use Twig_SimpleFilter to add a filter. The following classes and interfaces
will be removed in 2.0:
Twig_FilterInterface
Twig_FilterCallableInterface
PDF brought to you by
generated on April 16, 2014
Chapter 81: Deprecated Features | 158
Twig_Filter
Twig_Filter_Function
Twig_Filter_Method
Twig_Filter_Node
As of Twig 2.x, the Twig_SimpleFilter class is deprecated and will be removed in Twig 3.x
(use Twig_Filter instead). In Twig 2.x, Twig_SimpleFilter is just an alias for Twig_Filter.
Functions
As of Twig 1.x, use Twig_SimpleFunction to add a function. The following classes and
interfaces will be removed in 2.0:
Twig_FunctionInterface
Twig_FunctionCallableInterface
Twig_Function
Twig_Function_Function
Twig_Function_Method
Twig_Function_Node
As of Twig 2.x, the Twig_SimpleFunction class is deprecated and will be removed in Twig
3.x (use Twig_Function instead). In Twig 2.x, Twig_SimpleFunction is just an alias for
Twig_Function.
Tests
As of Twig 1.x, use Twig_SimpleTest to add a test. The following classes and interfaces will
be removed in 2.0:
Twig_TestInterface
Twig_TestCallableInterface
Twig_Test
Twig_Test_Function
Twig_Test_Method
Twig_Test_Node
As of Twig 2.x, the Twig_SimpleTest class is deprecated and will be removed in Twig 3.x (use
Twig_Test instead). In Twig 2.x, Twig_SimpleTest is just an alias for Twig_Test.
The sameas and divisibleby tests are deprecated in favor of same as and divisible by
respectively.
Interfaces
As of Twig 2.x, the following interfaces are deprecated and empty (they will be removed in
Twig 3.0):
Twig_CompilerInterface (use Twig_Compiler instead)
Twig_LexerInterface (use Twig_Lexer instead)
Twig_NodeInterface (use Twig_Node instead)
Twig_ParserInterface (use Twig_Parser instead)
Twig_ExistsLoaderInterface (merged with Twig_LoaderInterface)
PDF brought to you by
generated on April 16, 2014
Chapter 81: Deprecated Features | 159
Twig_TemplateInterface (use Twig_Template instead, and use those constants
Twig_Template::ANY_CALL, Twig_Template::ARRAY_CALL,
Twig_Template::METHOD_CALL)
Globals
As of Twig 2.x, the ability to register a global variable after the runtime or the extensions have
been initialized is not possible anymore (but changing the value of an already registered global
is possible).
PDF brought to you by
generated on April 16, 2014
Chapter 81: Deprecated Features | 160