# Twig for Template Designers
This document describes the syntax and semantics of the template engine andwill be most useful as reference to those creating Twig templates.
### Synopsis
A template is simply a text file. It can generate any text-based format (HTML,XML, CSV, LaTeX, etc.). It doesn't have a specific extension, `.html` or`.xml` are just fine.
A template contains **variables** or **expressions**, which get replaced withvalues when the template is evaluated, and **tags**, which control the logicof the template.
Below is a minimal template that illustrates a few basics. We will cover furtherdetails later on:
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre> 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16</pre></div></td><td class="code"><div class="highlight"><pre><!DOCTYPE html>
<html>
<head>
<title>My Webpage</title>
</head>
<body>
<ul id="navigation">
{% for item in navigation %}
<li><a href="{{ item.href }}">{{ item.caption }}</a></li>
{% endfor %}
</ul>
<h1>My Webpage</h1>
{{ a_variable }}
</body>
</html>
</pre></div></td></tr></table>
There are two kinds of delimiters: `{% ... %}` and `{{ ... }}`. The firstone is used to execute statements such as for-loops, the latter prints theresult of an expression to the template.
### IDEs Integration
Many IDEs support syntax highlighting and auto-completion for Twig:
- *Textmate* via the [Twig bundle](https://github.com/Anomareh/PHP-Twig.tmbundle) [https://github.com/Anomareh/PHP-Twig.tmbundle]
- *Vim* via the [Jinja syntax plugin](http://jinja.pocoo.org/docs/integration/#vim) [http://jinja.pocoo.org/docs/integration/#vim] or the [vim-twig plugin](https://github.com/evidens/vim-twig) [https://github.com/evidens/vim-twig]
- *Netbeans* via the [Twig syntax plugin](http://plugins.netbeans.org/plugin/37069/php-twig) [http://plugins.netbeans.org/plugin/37069/php-twig] (until 7.1, native as of 7.2)
- *PhpStorm* (native as of 2.1)
- *Eclipse* via the [Twig plugin](https://github.com/pulse00/Twig-Eclipse-Plugin) [https://github.com/pulse00/Twig-Eclipse-Plugin]
- *Sublime Text* via the [Twig bundle](https://github.com/Anomareh/PHP-Twig.tmbundle) [https://github.com/Anomareh/PHP-Twig.tmbundle]
- *GtkSourceView* via the [Twig language definition](https://github.com/gabrielcorpse/gedit-twig-template-language) [https://github.com/gabrielcorpse/gedit-twig-template-language] (used by gedit and other projects)
- *Coda* and *SubEthaEdit* via the [Twig syntax mode](https://github.com/bobthecow/Twig-HTML.mode) [https://github.com/bobthecow/Twig-HTML.mode]
- *Coda 2* via the [other Twig syntax mode](https://github.com/muxx/Twig-HTML.mode) [https://github.com/muxx/Twig-HTML.mode]
- *Komodo* and *Komodo Edit* via the Twig highlight/syntax check mode
- *Notepad++* via the [Notepad++ Twig Highlighter](https://github.com/Banane9/notepadplusplus-twig) [https://github.com/Banane9/notepadplusplus-twig]
- *Emacs* via [web-mode.el](http://web-mode.org/) [http://web-mode.org/]
- *Atom* via the [PHP-twig for atom](https://github.com/reesef/php-twig) [https://github.com/reesef/php-twig]
Also, [TwigFiddle](http://twigfiddle.com/) [http://twigfiddle.com/] is an online service that allows you to execute Twig templatesfrom a browser; it supports all versions of Twig.
### Variables
The application passes variables to the templates for manipulation in thetemplate. Variables may have attributes or elements you can access,too. The visual representation of a variable depends heavily on the application providingit.
You can use a dot (`.`) to access attributes of a variable (methods orproperties of a PHP object, or items of a PHP array), or the so-called"subscript" syntax (`[]`):
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1
2</pre></div></td><td class="code"><div class="highlight"><pre>{{ foo.bar }}
{{ foo['bar'] }}
</pre></div></td></tr></table>
When the attribute contains special characters (like `-` that would beinterpreted as the minus operator), use the `attribute` function instead toaccess the variable attribute:
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1
2</pre></div></td><td class="code"><div class="highlight"><pre>{# equivalent to the non-working foo.data-foo #}
{{ attribute(foo, 'data-foo') }}
</pre></div></td></tr></table>
Note
It's important to know that the curly braces are *not* part of thevariable but the print statement. When accessing variables inside tags,don't put the braces around them.
If a variable or attribute does not exist, you will receive a `null` valuewhen the `strict_variables` option is set to `false`; alternatively, if `strict_variables`is set, Twig will throw an error (see [*environment options*](#)).
Implementation
For convenience's sake `foo.bar` does the following things on the PHPlayer:
- check if `foo` is an array and `bar` a valid element;
- if not, and if `foo` is an object, check that `bar` is a valid property;
- if not, and if `foo` is an object, check that `bar` is a valid method(even if `bar` is the constructor - use `__construct()` instead);
- if not, and if `foo` is an object, check that `getBar` is a valid method;
- if not, and if `foo` is an object, check that `isBar` is a valid method;
- if not, return a `null` value.
`foo['bar']` on the other hand only works with PHP arrays:
- check if `foo` is an array and `bar` a valid element;
- if not, return a `null` value.
Note
If you want to access a dynamic attribute of a variable, use the[*attribute*](#) function instead.
### Global Variables
The following variables are always available in templates:
- `_self`: references the current template;
- `_context`: references the current context;
- `_charset`: references the current charset.
### Setting Variables
You can assign values to variables inside code blocks. Assignments use the[*set*](#) tag:
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1
2
3</pre></div></td><td class="code"><div class="highlight"><pre>{% set foo = 'foo' %}
{% set foo = [1, 2] %}
{% set foo = {'foo': 'bar'} %}
</pre></div></td></tr></table>
### Filters
Variables can be modified by **filters**. Filters are separated from thevariable by a pipe symbol (`|`) and may have optional arguments inparentheses. Multiple filters can be chained. The output of one filter isapplied to the next.
The following example removes all HTML tags from the `name` and title-casesit:
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1</pre></div></td><td class="code"><div class="highlight"><pre>{{ name|striptags|title }}
</pre></div></td></tr></table>
Filters that accept arguments have parentheses around the arguments. Thisexample will join a list by commas:
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1</pre></div></td><td class="code"><div class="highlight"><pre>{{ list|join(', ') }}
</pre></div></td></tr></table>
To apply a filter on a section of code, wrap it in the[*filter*](#) tag:
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1
2
3</pre></div></td><td class="code"><div class="highlight"><pre>{% filter upper %}
This text becomes uppercase
{% endfilter %}
</pre></div></td></tr></table>
Go to the [*filters*](#) page to learn more about built-infilters.
### Functions
Functions can be called to generate content. Functions are called by theirname followed by parentheses (`()`) and may have arguments.
For instance, the `range` function returns a list containing an arithmeticprogression of integers:
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1
2
3</pre></div></td><td class="code"><div class="highlight"><pre>{% for i in range(0, 3) %}
{{ i }},
{% endfor %}
</pre></div></td></tr></table>
Go to the [*functions*](#) page to learn more about thebuilt-in functions.
### Named Arguments
New in version 1.12: Support for named arguments was added in Twig 1.12.
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1
2
3</pre></div></td><td class="code"><div class="highlight"><pre>{% for i in range(low=1, high=10, step=2) %}
{{ i }},
{% endfor %}
</pre></div></td></tr></table>
Using named arguments makes your templates more explicit about the meaning ofthe values you pass as arguments:
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1
2
3
4
5</pre></div></td><td class="code"><div class="highlight"><pre>{{ data|convert_encoding('UTF-8', 'iso-2022-jp') }}
{# versus #}
{{ data|convert_encoding(from='iso-2022-jp', to='UTF-8') }}
</pre></div></td></tr></table>
Named arguments also allow you to skip some arguments for which you don't wantto change the default value:
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1
2
3
4
5</pre></div></td><td class="code"><div class="highlight"><pre>{# the first argument is the date format, which defaults to the global date format if null is passed #}
{{ "now"|date(null, "Europe/Paris") }}
{# or skip the format value by using a named argument for the time zone #}
{{ "now"|date(timezone="Europe/Paris") }}
</pre></div></td></tr></table>
You can also use both positional and named arguments in one call, in whichcase positional arguments must always come before named arguments:
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1</pre></div></td><td class="code"><div class="highlight"><pre>{{ "now"|date('d/m/Y H:i', timezone="Europe/Paris") }}
</pre></div></td></tr></table>
Tip
Each function and filter documentation page has a section where the namesof all arguments are listed when supported.
### Control Structure
A control structure refers to all those things that control the flow of aprogram - conditionals (i.e. `if`/`elseif`/`else`), `for`-loops, aswell as things like blocks. Control structures appear inside `{% ... %}`blocks.
For example, to display a list of users provided in a variable called`users`, use the [*for*](#) tag:
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1
2
3
4
5
6</pre></div></td><td class="code"><div class="highlight"><pre><h1>Members</h1>
<ul>
{% for user in users %}
<li>{{ user.username|e }}</li>
{% endfor %}
</ul>
</pre></div></td></tr></table>
The [*if*](#) tag can be used to test an expression:
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1
2
3
4
5
6
7</pre></div></td><td class="code"><div class="highlight"><pre>{% if users|length > 0 %}
<ul>
{% for user in users %}
<li>{{ user.username|e }}</li>
{% endfor %}
</ul>
{% endif %}
</pre></div></td></tr></table>
Go to the [*tags*](#) page to learn more about the built-in tags.
### Comments
To comment-out part of a line in a template, use the comment syntax `{# ...#}`. This is useful for debugging or to add information for other templatedesigners or yourself:
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1
2
3
4
5</pre></div></td><td class="code"><div class="highlight"><pre>{# note: disabled template because we no longer use this
{% for user in users %}
...
{% endfor %}
#}
</pre></div></td></tr></table>
### Including other Templates
The [*include*](#) tag is useful to include a template andreturn the rendered content of that template into the current one:
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1</pre></div></td><td class="code"><div class="highlight"><pre>{% include 'sidebar.html' %}
</pre></div></td></tr></table>
Per default included templates are passed the current context.
The context that is passed to the included template includes variables definedin the template:
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1
2
3</pre></div></td><td class="code"><div class="highlight"><pre>{% for box in boxes %}
{% include "render_box.html" %}
{% endfor %}
</pre></div></td></tr></table>
The included template `render_box.html` is able to access `box`.
The filename of the template depends on the template loader. For instance, the`Twig_Loader_Filesystem` allows you to access other templates by giving thefilename. You can access templates in subdirectories with a slash:
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1</pre></div></td><td class="code"><div class="highlight"><pre>{% include "sections/articles/sidebar.html" %}
</pre></div></td></tr></table>
This behavior depends on the application embedding Twig.
### Template Inheritance
The most powerful part of Twig is template inheritance. Template inheritanceallows you to build a base "skeleton" template that contains all the commonelements of your site and defines **blocks** that child templates canoverride.
Sounds complicated but it is very basic. It's easier to understand it bystarting with an example.
Let's define a base template, `base.html`, which defines a simple HTMLskeleton document that you might use for a simple two-column page:
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre> 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17</pre></div></td><td class="code"><div class="highlight"><pre><!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 %}
&copy; Copyright 2011 by <a href="http://domain.invalid/">you</a>.
{% endblock %}
</div>
</body>
</html>
</pre></div></td></tr></table>
In this example, the [*block*](#) tags define four blocks thatchild templates can fill in. All the `block` tag does is to tell thetemplate engine that a child template may override those portions of thetemplate.
A child template might look like this:
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre> 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15</pre></div></td><td class="code"><div class="highlight"><pre>{% 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 to my awesome homepage.
</p>
{% endblock %}
</pre></div></td></tr></table>
The [*extends*](#) tag is the key here. It tells the templateengine that this template "extends" another template. When the template systemevaluates this template, first it locates the parent. The extends tag shouldbe the first tag in the template.
Note that since the child template doesn't define the `footer` block, thevalue from the parent template is used instead.
It's possible to render the contents of the parent block by using the[*parent*](#) function. This gives back the results of theparent block:
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1
2
3
4
5</pre></div></td><td class="code"><div class="highlight"><pre>{% block sidebar %}
<h3>Table Of Contents</h3>
...
{{ parent() }}
{% endblock %}
</pre></div></td></tr></table>
Tip
The documentation page for the [*extends*](#) tag describesmore advanced features like block nesting, scope, dynamic inheritance, andconditional inheritance.
Note
Twig also supports multiple inheritance with the so called horizontal reusewith the help of the [*use*](#) tag. This is an advanced featurehardly ever needed in regular templates.
### HTML Escaping
When generating HTML from templates, there's always a risk that a variablewill include characters that affect the resulting HTML. There are twoapproaches: manually escaping each variable or automatically escapingeverything by default.
Twig supports both, automatic escaping is enabled by default.
Note
Automatic escaping is only supported if the *escaper* extension has beenenabled (which is the default).
### Working with Manual Escaping
If manual escaping is enabled, it is **your** responsibility to escapevariables if needed. What to escape? Any variable you don't trust.
Escaping works by piping the variable through the[*escape*](#) or `e` filter:
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1</pre></div></td><td class="code"><div class="highlight"><pre>{{ user.username|e }}
</pre></div></td></tr></table>
By default, the `escape` filter uses the `html` strategy, but depending onthe escaping context, you might want to explicitly use any other availablestrategies:
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1
2
3
4</pre></div></td><td class="code"><div class="highlight"><pre>{{ user.username|e('js') }}
{{ user.username|e('css') }}
{{ user.username|e('url') }}
{{ user.username|e('html_attr') }}
</pre></div></td></tr></table>
### Working with Automatic Escaping
Whether automatic escaping is enabled or not, you can mark a section of atemplate to be escaped or not by using the [*autoescape*](#)tag:
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1
2
3</pre></div></td><td class="code"><div class="highlight"><pre>{% autoescape %}
Everything will be automatically escaped in this block (using the HTML strategy)
{% endautoescape %}
</pre></div></td></tr></table>
By default, auto-escaping uses the `html` escaping strategy. If you outputvariables in other contexts, you need to explicitly escape them with theappropriate escaping strategy:
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1
2
3</pre></div></td><td class="code"><div class="highlight"><pre>{% autoescape 'js' %}
Everything will be automatically escaped in this block (using the JS strategy)
{% endautoescape %}
</pre></div></td></tr></table>
### Escaping
It is sometimes desirable or even necessary to have Twig ignore parts it wouldotherwise handle as variables or blocks. For example if the default syntax isused and you want to use `{{` as raw string in the template and not start avariable you have to use a trick.
The easiest way is to output the variable delimiter (`{{`) by using a variableexpression:
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1</pre></div></td><td class="code"><div class="highlight"><pre>{{ '{{' }}
</pre></div></td></tr></table>
For bigger sections it makes sense to mark a block[*verbatim*](#).
### Macros
New in version 1.12: Support for default argument values was added in Twig 1.12.
Macros are comparable with functions in regular programming languages. Theyare useful to reuse often used HTML fragments to not repeat yourself.
A macro is defined via the [*macro*](#) tag. Here is a small example(subsequently called `forms.html`) of a macro that renders a form element:
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1
2
3</pre></div></td><td class="code"><div class="highlight"><pre>{% macro input(name, value, type, size) %}
<input type="{{ type|default('text') }}" name="{{ name }}" value="{{ value|e }}" size="{{ size|default(20) }}" />
{% endmacro %}
</pre></div></td></tr></table>
Macros can be defined in any template, and need to be "imported" via the[*import*](#) tag before being used:
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1
2
3</pre></div></td><td class="code"><div class="highlight"><pre>{% import "forms.html" as forms %}
<p>{{ forms.input('username') }}</p>
</pre></div></td></tr></table>
Alternatively, you can import individual macro names from a template into thecurrent namespace via the [*from*](#) tag and optionally alias them:
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1
2
3
4
5
6
7
8</pre></div></td><td class="code"><div class="highlight"><pre>{% from 'forms.html' import input as input_field %}
<dl>
<dt>Username</dt>
<dd>{{ input_field('username') }}</dd>
<dt>Password</dt>
<dd>{{ input_field('password', '', 'password') }}</dd>
</dl>
</pre></div></td></tr></table>
A default value can also be defined for macro arguments when not provided in amacro call:
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1
2
3</pre></div></td><td class="code"><div class="highlight"><pre>{% macro input(name, value = "", type = "text", size = 20) %}
<input type="{{ type }}" name="{{ name }}" value="{{ value|e }}" size="{{ size }}" />
{% endmacro %}
</pre></div></td></tr></table>
If extra positional arguments are passed to a macro call, they end up in thespecial `varargs` variable as a list of values.
### Expressions
Twig allows expressions everywhere. These work very similar to regular PHP andeven if you're not working with PHP you should feel comfortable with it.
Note
The operator precedence is as follows, with the lowest-precedenceoperators listed first: `b-and`, `b-xor`, `b-or`, `or`, `and`,`==`, `!=`, `<`, `>`, `>=`, `<=`, `in`, `matches`,`starts with`, `ends with`, `..`, `+`, `-`, `~`, `*`, `/`,`//`, `%`, `is`, `**`, `|`, `[]`, and `.`:
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1
2
3
4
5
6
7</pre></div></td><td class="code"><div class="highlight"><pre>{% set greeting = 'Hello ' %}
{% set name = 'Fabien' %}
{{ greeting ~ name|lower }} {# Hello fabien #}
{# use parenthesis to change precedence #}
{{ (greeting ~ name)|lower }} {# hello fabien #}
</pre></div></td></tr></table>
### Literals
New in version 1.5: Support for hash keys as names and expressions was added in Twig 1.5.
The simplest form of expressions are literals. Literals are representationsfor PHP types such as strings, numbers, and arrays. The following literalsexist:
-
`"Hello World"`: Everything between two double or single quotes is astring. They are useful whenever you need a string in the template (forexample as arguments to function calls, filters or just to extend or includea template). A string can contain a delimiter if it is preceded by abackslash (`\`) -- like in `'It\'s good'`.
-
`42` / `42.23`: Integers and floating point numbers are created by justwriting the number down. If a dot is present the number is a float,otherwise an integer.
-
`["foo", "bar"]`: Arrays are defined by a sequence of expressionsseparated by a comma (`,`) and wrapped with squared brackets (`[]`).
-
`{"foo": "bar"}`: Hashes are defined by a list of keys and valuesseparated by a comma (`,`) and wrapped with curly braces (`{}`):
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre> 1
2
3
4
5
6
7
8
9
10
11</pre></div></td><td class="code"><div class="highlight"><pre>{# keys as string #}
{ 'foo': 'foo', 'bar': 'bar' }
{# keys as names (equivalent to the previous hash) -- as of Twig 1.5 #}
{ foo: 'foo', bar: 'bar' }
{# keys as integer #}
{ 2: 'foo', 4: 'bar' }
{# keys as expressions (the expression must be enclosed into parentheses) -- as of Twig 1.5 #}
{ (1 + 1): 'foo', (a ~ 'b'): 'bar' }
</pre></div></td></tr></table>
-
`true` / `false`: `true` represents the true value, `false`represents the false value.
-
`null`: `null` represents no specific value. This is the value returnedwhen a variable does not exist. `none` is an alias for `null`.
Arrays and hashes can be nested:
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1</pre></div></td><td class="code"><div class="highlight"><pre>{% set foo = [1, {"foo": "bar"}] %}
</pre></div></td></tr></table>
Tip
Using double-quoted or single-quoted strings has no impact on performancebut string interpolation is only supported in double-quoted strings.
### Math
Twig allows you to calculate with values. This is rarely useful in templatesbut exists for completeness' sake. The following operators are supported:
- `+`: Adds two objects together (the operands are casted to numbers). `{{1 + 1 }}` is `2`.
- `-`: Subtracts the second number from the first one. `{{ 3 - 2 }}` is`1`.
- `/`: Divides two numbers. The returned value will be a floating pointnumber. `{{ 1 / 2 }}` is `{{ 0.5 }}`.
- `%`: Calculates the remainder of an integer division. `{{ 11 % 7 }}` is`4`.
- `//`: Divides two numbers and returns the floored integer result. `{{ 20// 7 }}` is `2`, `{{ -20 // 7 }}` is `-3` (this is just syntacticsugar for the [*round*](#) filter).
- `*`: Multiplies the left operand with the right one. `{{ 2 * 2 }}` wouldreturn `4`.
- `**`: Raises the left operand to the power of the right operand. `{{ 2 **3 }}` would return `8`.
### Logic
You can combine multiple expressions with the following operators:
- `and`: Returns true if the left and the right operands are both true.
- `or`: Returns true if the left or the right operand is true.
- `not`: Negates a statement.
- `(expr)`: Groups an expression.
Note
Twig also support bitwise operators (`b-and`, `b-xor`, and `b-or`).
Note
Operators are case sensitive.
### Comparisons
The following comparison operators are supported in any expression: `==`,`!=`, `<`, `>`, `>=`, and `<=`.
You can also check if a string `starts with` or `ends with` anotherstring:
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1
2
3
4
5</pre></div></td><td class="code"><div class="highlight"><pre>{% if 'Fabien' starts with 'F' %}
{% endif %}
{% if 'Fabien' ends with 'n' %}
{% endif %}
</pre></div></td></tr></table>
Note
For complex string comparisons, the `matches` operator allows you to use[regular expressions](http://php.net/manual/en/pcre.pattern.php) [http://php.net/manual/en/pcre.pattern.php]:
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1
2</pre></div></td><td class="code"><div class="highlight"><pre>{% if phone matches '/^[\\d\\.]+$/' %}
{% endif %}
</pre></div></td></tr></table>
### Containment Operator
The `in` operator performs containment test.
It returns `true` if the left operand is contained in the right:
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1
2
3
4
5</pre></div></td><td class="code"><div class="highlight"><pre>{# returns true #}
{{ 1 in [1, 2, 3] }}
{{ 'cd' in 'abcde' }}
</pre></div></td></tr></table>
Tip
You can use this filter to perform a containment test on strings, arrays,or objects implementing the `Traversable` interface.
To perform a negative test, use the `not in` operator:
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1
2
3
4</pre></div></td><td class="code"><div class="highlight"><pre>{% if 1 not in [1, 2, 3] %}
{# is equivalent to #}
{% if not (1 in [1, 2, 3]) %}
</pre></div></td></tr></table>
### Test Operator
The `is` operator performs tests. Tests can be used to test a variable againsta common expression. The right operand is name of the test:
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1
2
3</pre></div></td><td class="code"><div class="highlight"><pre>{# find out if a variable is odd #}
{{ name is odd }}
</pre></div></td></tr></table>
Tests can accept arguments too:
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1</pre></div></td><td class="code"><div class="highlight"><pre>{% if post.status is constant('Post::PUBLISHED') %}
</pre></div></td></tr></table>
Tests can be negated by using the `is not` operator:
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1
2
3
4</pre></div></td><td class="code"><div class="highlight"><pre>{% if post.status is not constant('Post::PUBLISHED') %}
{# is equivalent to #}
{% if not (post.status is constant('Post::PUBLISHED')) %}
</pre></div></td></tr></table>
Go to the [*tests*](#) page to learn more about the built-intests.
### Other Operators
New in version 1.12.0: Support for the extended ternary operator was added in Twig 1.12.0.
The following operators don't fit into any of the other categories:
-
`|`: Applies a filter.
-
`..`: Creates a sequence based on the operand before and after the operator(this is just syntactic sugar for the [*range*](#) function):
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1
2
3
4</pre></div></td><td class="code"><div class="highlight"><pre>{{ 1..5 }}
{# equivalent to #}
{{ range(1, 5) }}
</pre></div></td></tr></table>
Note that you must use parentheses when combining it with the filter operatordue to the [*operator precedence rules*](#):
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1</pre></div></td><td class="code"><div class="highlight"><pre>(1..5)|join(', ')
</pre></div></td></tr></table>
-
`~`: Converts all operands into strings and concatenates them. `{{ "Hello" ~ name ~ "!" }}` would return (assuming `name` is `'John'`) `HelloJohn!`.
-
`.`, `[]`: Gets an attribute of an object.
-
`?:`: The ternary operator:
~~~
{{ foo ? 'yes' : 'no' }}
{# as of Twig 1.12.0 #}
{{ foo ?: 'no' }} is the same as {{ foo ? foo : 'no' }}
{{ foo ? 'yes' }} is the same as {{ foo ? 'yes' : '' }}
~~~
-
`??`: The null-coalescing operator:
~~~
{# returns the value of foo if it is defined and not null, 'no' otherwise #}
{{ foo ?? 'no' }}
~~~
### String Interpolation
New in version 1.5: String interpolation was added in Twig 1.5.
String interpolation (#{expression}) allows any valid expression to appearwithin a *double-quoted string*. The result of evaluating that expression isinserted into the string:
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1
2</pre></div></td><td class="code"><div class="highlight"><pre>{{ "foo #{bar} baz" }}
{{ "foo #{1 + 2} baz" }}
</pre></div></td></tr></table>
### Whitespace Control
New in version 1.1: Tag level whitespace control was added in Twig 1.1.
The first newline after a template tag is removed automatically (like in PHP.)Whitespace is not further modified by the template engine, so each whitespace(spaces, tabs, newlines etc.) is returned unchanged.
Use the `spaceless` tag to remove whitespace *between HTML tags*:
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1
2
3
4
5
6
7</pre></div></td><td class="code"><div class="highlight"><pre>{% spaceless %}
<div>
<strong>foo bar</strong>
</div>
{% endspaceless %}
{# output will be <div><strong>foo bar</strong></div> #}
</pre></div></td></tr></table>
In addition to the spaceless tag you can also control whitespace on a per taglevel. By using the whitespace control modifier on your tags, you can trimleading and or trailing whitespace:
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1
2
3
4
5
6
7</pre></div></td><td class="code"><div class="highlight"><pre>{% set value = 'no spaces' %}
{#- No leading/trailing whitespace -#}
{%- if true -%}
{{- value -}}
{%- endif -%}
{# output 'no spaces' #}
</pre></div></td></tr></table>
The above sample shows the default whitespace control modifier, and how you canuse it to remove whitespace around tags. Trimming space will consume all whitespacefor that side of the tag. It is possible to use whitespace trimming on one sideof a tag:
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1
2
3
4</pre></div></td><td class="code"><div class="highlight"><pre>{% set value = 'no spaces' %}
<li> {{- value }} </li>
{# outputs '<li>no spaces </li>' #}
</pre></div></td></tr></table>
### Extensions
Twig can be easily extended.
If you are looking for new tags, filters, or functions, have a look at the Twig official[extension repository](http://github.com/twigphp/Twig-extensions) [http://github.com/twigphp/Twig-extensions].
If you want to create your own, read the [*Creating anExtension*](#) chapter.
- Twig
- Introduction
- Installation
- Twig for Template Designers
- Twig for Developers
- Extending Twig
- Twig Internals
- Deprecated Features
- Recipes
- Coding Standards
- Tags
- autoescape
- block
- do
- embed
- extends
- filter
- flush
- for
- from
- if
- import
- include
- macro
- sandbox
- set
- spaceless
- use
- verbatim
- Filters
- abs
- batch
- capitalize
- convert_encoding
- date
- date_modify
- default
- escape
- first
- format
- join
- json_encode
- keys
- last
- length
- lower
- merge
- nl2br
- number_format
- raw
- replace
- reverse
- round
- slice
- sort
- split
- striptags
- title
- trim
- upper
- url_encode
- Functions
- attribute
- block
- constant
- cycle
- date
- dump
- include
- max
- min
- parent
- random
- range
- source
- template_from_string
- Tests
- constant
- defined
- divisible by
- empty
- even
- iterable
- null
- odd
- same as