tweaked the doc

This commit is contained in:
Fabien Potencier
2019-04-27 12:22:50 +01:00
parent bf3781c9c1
commit 5ac239ca4f
7 changed files with 172 additions and 230 deletions
+43 -47
View File
@@ -13,10 +13,10 @@ itself with node visitors.
.. note::
The first section of this chapter describes how to extend Twig easily. If
you want to reuse your changes in different projects or if you want to
share them with others, you should then create an extension as described
in the following section.
The first section of this chapter describes how to extend Twig. If you want
to reuse your changes in different projects or if you want to share them
with others, you should then create an extension as described in the
following section.
.. caution::
@@ -56,7 +56,7 @@ three main reasons:
{{ 'some text' ~ {% lipsum 40 %} ~ 'some more text' }}
In fact, you rarely need to create tags; and that's good news because tags are
the most complex extension point of Twig.
the most complex extension point.
Now, let's use a ``lipsum`` *filter*:
@@ -64,10 +64,9 @@ Now, let's use a ``lipsum`` *filter*:
{{ 40|lipsum }}
Again, it works, but it looks weird. A filter transforms the passed value to
something else but here we use the value to indicate the number of words to
generate (so, ``40`` is an argument of the filter, not the value we want to
transform).
Again, it works. But a filter should transform the passed value to something
else. Here, we use the value to indicate the number of words to generate (so,
``40`` is an argument of the filter, not the value we want to transform).
Next, let's use a ``lipsum`` *function*:
@@ -84,8 +83,8 @@ extension point to use. And you can use it anywhere an expression is accepted:
{% set lipsum = lipsum(40) %}
Last but not the least, you can also use a *global* object with a method able
to generate lorem ipsum text:
Lastly, you can also use a *global* object with a method able to generate lorem
ipsum text:
.. code-block:: twig
@@ -99,13 +98,13 @@ Keep in mind the following when you want to extend Twig:
========== ========================== ========== =========================
What? Implementation difficulty? How often? When?
========== ========================== ========== =========================
*macro* trivial frequent Content generation
*global* trivial frequent Helper object
*function* trivial frequent Content generation
*filter* trivial frequent Value transformation
*macro* simple frequent Content generation
*global* simple frequent Helper object
*function* simple frequent Content generation
*filter* simple frequent Value transformation
*tag* complex rare DSL language construct
*test* trivial rare Boolean decision
*operator* trivial rare Values transformation
*test* simple rare Boolean decision
*operator* simple rare Values transformation
========== ========================== ========== =========================
Globals
@@ -126,7 +125,7 @@ You can then use the ``text`` variable anywhere in a template:
Filters
-------
Creating a filter is as simple as associating a name with a PHP callable::
Creating a filter consists of associating a name with a PHP callable::
// an anonymous function
$filter = new \Twig\TwigFilter('rot13', function ($string) {
@@ -149,7 +148,7 @@ The first argument passed to the ``\Twig\TwigFilter`` constructor is the name
of the filter you will use in templates and the second one is the PHP callable
to associate with it.
Then, add the filter to your Twig environment::
Then, add the filter to the Twig environment::
$twig = new \Twig\Environment($loader);
$twig->addFilter($filter);
@@ -251,14 +250,14 @@ option array.
Dynamic Filters
~~~~~~~~~~~~~~~
A filter name containing the special ``*`` character is a dynamic filter as
the ``*`` can be any string::
A filter name containing the special ``*`` character is a dynamic filter and
the ``*`` part will match any string::
$filter = new \Twig\TwigFilter('*_path', function ($name, $arguments) {
// ...
});
The following filters will be matched by the above defined dynamic filter:
The following filters are matched by the above defined dynamic filter:
* ``product_path``
* ``category_path``
@@ -269,10 +268,10 @@ A dynamic filter can define more than one dynamic parts::
// ...
});
The filter will receive all dynamic part values before the normal filter
arguments, but after the environment and the context. For instance, a call to
``'foo'|a_path_b()`` will result in the following arguments to be passed to
the filter: ``('a', 'b', 'foo')``.
The filter receives all dynamic part values before the normal filter arguments,
but after the environment and the context. For instance, a call to
``'foo'|a_path_b()`` will result in the following arguments to be passed to the
filter: ``('a', 'b', 'foo')``.
Deprecated Filters
~~~~~~~~~~~~~~~~~~
@@ -334,7 +333,7 @@ objects are 'red'::
});
$twig->addTest($test);
Test functions should always return true/false.
Test functions must always return ``true``/``false``.
When creating tests you can use the ``node_class`` option to provide custom test
compilation. This is useful if your test can be compiled into PHP primitives.
@@ -360,8 +359,8 @@ This is used by many of the tests built into Twig::
}
}
The above example shows how you can create tests that use a node class. The
node class has access to one sub-node called 'node'. This sub-node contains the
The above example shows how you can create tests that use a node class. The node
class has access to one sub-node called ``node``. This sub-node contains the
value that is being tested. When the ``odd`` filter is used in code such as:
.. code-block:: twig
@@ -377,7 +376,7 @@ various other arguments that have been provided to your test.
If you want to pass a variable number of positional or named arguments to the
test, set the ``is_variadic`` option to ``true``. Tests support dynamic
names (see dynamic filters and functions for the syntax).
names (see dynamic filters for the syntax).
Tags
----
@@ -429,8 +428,8 @@ Most of the time though, a tag is not needed:
If you still want to create a tag for a new language construct, great!
Let's create a simple ``set`` tag that allows the definition of simple
variables from within a template. The tag can be used like follows:
Let's create a ``set`` tag that allows the definition of simple variables from
within a template. The tag can be used like follows:
.. code-block:: twig
@@ -444,8 +443,7 @@ variables from within a template. The tag can be used like follows:
The ``set`` tag is part of the Core extension and as such is always
available. The built-in version is slightly more powerful and supports
multiple assignments by default (cf. the template designers chapter for
more information).
multiple assignments by default.
Three steps are needed to define a new tag:
@@ -458,8 +456,8 @@ Three steps are needed to define a new tag:
Registering a new tag
~~~~~~~~~~~~~~~~~~~~~
Adding a tag is as simple as calling the ``addTokenParser`` method on the
``\Twig\Environment`` instance::
Add a tag by calling the ``addTokenParser`` method on the ``\Twig\Environment``
instance::
$twig = new \Twig\Environment($loader);
$twig->addTokenParser(new Project_Set_TokenParser());
@@ -524,7 +522,7 @@ the ``set`` tag.
Defining a Node
~~~~~~~~~~~~~~~
The ``Project_Set_Node`` class itself is rather simple::
The ``Project_Set_Node`` class itself is quite short::
class Project_Set_Node extends \Twig\Node\Node
{
@@ -575,8 +573,7 @@ Creating an Extension
The main motivation for writing an extension is to move often used code into a
reusable class like adding support for internationalization. An extension can
define tags, filters, tests, operators, global variables, functions, and node
visitors.
define tags, filters, tests, operators, functions, and node visitors.
Most of the time, it is useful to create a single extension for your project,
to host all the specific tags and filters you want to add to Twig.
@@ -674,16 +671,15 @@ empty implementations for all methods:
{
}
Of course, this extension does nothing for now. We will customize it in the
next sections.
This extension does nothing for now. We will customize it in the next sections.
.. note::
Prior to Twig 1.26, you must implement the ``getName()`` method which must
return a unique identifier for the extension.
Twig does not care where you save your extension on the filesystem, as all
extensions must be registered explicitly to be available in your templates.
You can save your extension anywhere on the filesystem, as all extensions must
be registered explicitly to be available in your templates.
You can register an extension by using the ``addExtension()`` method on your
main ``Environment`` object::
@@ -775,7 +771,7 @@ Operators
~~~~~~~~~
The ``getOperators()`` methods lets you add new operators. Here is how to add
``!``, ``||``, and ``&&`` operators::
the ``!``, ``||``, and ``&&`` operators::
class Project_Twig_Extension extends \Twig\Extension\AbstractExtension
{
@@ -880,7 +876,7 @@ instance on the environment that knows how to instantiate such runtime classes
.. note::
As of Twig 1.32, Twig comes with a PSR-11 compatible runtime loader
(``\Twig\RuntimeLoader\ContainerRuntimeLoader``) that works on PHP 5.3+.
(``\Twig\RuntimeLoader\ContainerRuntimeLoader``).
It is now possible to move the runtime logic to a new
``Project_Twig_RuntimeExtension`` class and use it directly in the extension::
@@ -961,8 +957,8 @@ Testing an Extension
Functional Tests
~~~~~~~~~~~~~~~~
You can create functional tests for extensions simply by creating the
following file structure in your test directory::
You can create functional tests for extensions by creating the following file
structure in your test directory::
Fixtures/
filters/
+48 -42
View File
@@ -10,16 +10,14 @@ Basics
Twig uses a central object called the **environment** (of class
``\Twig\Environment``). Instances of this class are used to store the
configuration and extensions, and are used to load templates from the file
system or other locations.
configuration and extensions, and are used to load templates.
Most applications will create one ``\Twig\Environment`` object on application
initialization and use that to load templates. In some cases it's however
useful to have multiple environments side by side, if different configurations
are in use.
Most applications create one ``\Twig\Environment`` object on application
initialization and use that to load templates. In some cases, it might be useful
to have multiple environments side by side, with different configurations.
The simplest way to configure Twig to load templates for your application
looks roughly like this::
The typical way to configure Twig to load templates for an application looks
roughly like this::
require_once '/path/to/lib/Twig/Autoloader.php';
Twig_Autoloader::register();
@@ -29,8 +27,8 @@ looks roughly like this::
'cache' => '/path/to/compilation_cache',
]);
This will create a template environment with the default settings and a loader
that looks up the templates in the ``/path/to/templates/`` folder. Different
This creates a template environment with a default configuration and a loader
that looks up templates in the ``/path/to/templates/`` directory. Different
loaders are available and you can also write your own if you want to load
templates from a database or other resources.
@@ -53,7 +51,7 @@ returns a ``\Twig\TemplateWrapper`` instance::
.. note::
Before Twig 1.28, you should use ``loadTemplate()`` instead which returns a
Before Twig 1.28, use ``loadTemplate()`` instead which returns a
``\Twig\Template`` instance.
To render the template with some variables, call the ``render()`` method::
@@ -62,7 +60,7 @@ To render the template with some variables, call the ``render()`` method::
.. note::
The ``display()`` method is a shortcut to output the template directly.
The ``display()`` method is a shortcut to output the rendered template.
You can also load and render the template in one fell swoop::
@@ -157,14 +155,14 @@ Compilation Cache
All template loaders can cache the compiled templates on the filesystem for
future reuse. It speeds up Twig a lot as templates are only compiled once; and
the performance boost is even larger if you use a PHP accelerator such as APC.
See the ``cache`` and ``auto_reload`` options of ``\Twig\Environment`` above
for more information.
the performance boost is even larger if you use a PHP accelerator such as
OPCache. See the ``cache`` and ``auto_reload`` options of ``\Twig\Environment``
above for more information.
Built-in Loaders
~~~~~~~~~~~~~~~~
Here is a list of the built-in loaders Twig provides:
Here is a list of the built-in loaders:
``\Twig\Loader\FilesystemLoader``
.................................
@@ -224,8 +222,8 @@ the directory might be different from the one used on production servers)::
``\Twig\Loader\ArrayLoader``
............................
``\Twig\Loader\ArrayLoader`` loads a template from a PHP array. It's passed an array
of strings bound to template names::
``\Twig\Loader\ArrayLoader`` loads a template from a PHP array. It is passed an
array of strings bound to template names::
$loader = new \Twig\Loader\ArrayLoader([
'index.html' => 'Hello {{ name }}!',
@@ -239,11 +237,11 @@ projects where storing all templates in a single PHP file might make sense.
.. tip::
When using the ``Array`` or ``String`` loaders with a cache mechanism, you
should know that a new cache key is generated each time a template content
"changes" (the cache key being the source code of the template). If you
don't want to see your cache grows out of control, you need to take care
of clearing the old cache file by yourself.
When using the ``Array``loaders with a cache mechanism, you should know that
a new cache key is generated each time a template content "changes" (the
cache key being the source code of the template). If you don't want to see
your cache grows out of control, you need to take care of clearing the old
cache file by yourself.
``\Twig\Loader\ChainLoader``
............................
@@ -262,13 +260,10 @@ projects where storing all templates in a single PHP file might make sense.
$twig = new \Twig\Environment($loader);
When looking for a template, Twig will try each loader in turn and it will
return as soon as the template is found. When rendering the ``index.html``
template from the above example, Twig will load it with ``$loader2`` but the
``base.html`` template will be loaded from ``$loader1``.
``\Twig\Loader\ChainLoader`` accepts any loader that implements
``\Twig\Loader\LoaderInterface``.
When looking for a template, Twig tries each loader in turn and returns as soon
as the template is found. When rendering the ``index.html`` template from the
above example, Twig will load it with ``$loader2`` but the ``base.html``
template will be loaded from ``$loader1``.
.. note::
@@ -326,28 +321,34 @@ is still fresh, given the last modification time, or ``false`` otherwise.
Using Extensions
----------------
Twig extensions are packages that add new features to Twig. Using an
extension is as simple as using the ``addExtension()`` method::
Twig extensions are packages that add new features to Twig. Register an
extension via the ``addExtension()`` method::
$twig->addExtension(new \Twig\Extension\SandboxExtension());
Twig comes bundled with the following extensions:
* *Twig_Extension_Core*: Defines all the core features of Twig.
* *Twig\Extension\CoreExtension*: Defines all the core features of Twig.
* *Twig_Extension_Escaper*: Adds automatic output-escaping and the possibility
to escape/unescape blocks of code.
* *Twig\Extension\DebugExtension*: Defines the ``dump`` function to help debug
template variables.
* *Twig_Extension_Sandbox*: Adds a sandbox mode to the default Twig
* *Twig\Extension\EscaperExtension*: Adds automatic output-escaping and the
possibility to escape/unescape blocks of code.
* *Twig\Extension\SandboxExtension*: Adds a sandbox mode to the default Twig
environment, making it safe to evaluate untrusted code.
* *Twig_Extension_Profiler*: Enabled the built-in Twig profiler (as of Twig
1.18).
* *Twig\Extension\ProfilerExtension*: Enabled the built-in Twig profiler (as of
Twig 1.18).
* *Twig_Extension_Optimizer*: Optimizes the node tree before compilation.
* *Twig\Extension\OptimizerExtension*: Optimizes the node tree before
compilation.
The core, escaper, and optimizer extensions do not need to be added to the
Twig environment, as they are registered by default.
* *Twig\Extension\StringLoaderExtension*: Defined the ``template_from_string``
function to allow loading templates from string in a template.
The Core, Escaper, and Optimizer extensions are registered by default.
Built-in Extensions
-------------------
@@ -537,7 +538,8 @@ compatible format::
file_put_contents('/path/to/profile.prof', $dumper->dump($profile));
Upload the profile to visualize it (create a `free account
<https://blackfire.io/signup>`_ first):
<https://blackfire.io/signup?utm_source=twig&utm_medium=doc&utm_campaign=profiler>`_
first):
.. code-block:: sh
@@ -561,13 +563,17 @@ Twig supports the following optimizations:
* ``\Twig\NodeVisitor\OptimizerNodeVisitor::OPTIMIZE_ALL``, enables all optimizations
(this is the default value).
* ``\Twig\NodeVisitor\OptimizerNodeVisitor::OPTIMIZE_NONE``, disables all optimizations.
This reduces the compilation time, but it can increase the execution time
and the consumed memory.
* ``\Twig\NodeVisitor\OptimizerNodeVisitor::OPTIMIZE_FOR``, optimizes the ``for`` tag by
removing the ``loop`` variable creation whenever possible.
* ``\Twig\NodeVisitor\OptimizerNodeVisitor::OPTIMIZE_RAW_FILTER``, removes the ``raw``
filter whenever possible.
* ``\Twig\NodeVisitor\OptimizerNodeVisitor::OPTIMIZE_VAR_ACCESS``, simplifies the creation
and access of variables in the compiled templates whenever possible.
+13 -57
View File
@@ -6,42 +6,11 @@ You have multiple ways to install Twig.
Installing the Twig PHP package
-------------------------------
Installing via Composer (recommended)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Install `Composer`_ and run the following command to get the latest version:
Install `Composer`_ and run the following command:
.. code-block:: bash
composer require twig/twig:~1.0
Installing from the tarball release
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1. Download the most recent tarball from the `download page`_
2. Verify the integrity of the tarball http://fabien.potencier.org/article/73/signing-project-releases
3. Unpack the tarball
4. Move the files somewhere in your project
Installing the development version
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. code-block:: bash
git clone git://github.com/twigphp/Twig.git
Installing the PEAR package
~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. note::
Using PEAR for installing Twig is deprecated and Twig 1.15.1 was the last
version published on the PEAR channel; use Composer instead.
.. code-block:: bash
pear channel-discover pear.twig-project.org
pear install twig/Twig
composer require "twig/twig:^1.0"
Installing the C extension
--------------------------
@@ -49,16 +18,16 @@ Installing the C extension
.. versionadded:: 1.4
The C extension was added in Twig 1.4.
.. note::
Twig comes with an **optional** C extension that improves the performance of the
Twig runtime engine.
The C extension is **optional** but it brings some nice performance
improvements. Note that the extension is not a replacement for the PHP
code; it only implements a small part of the PHP code to improve the
performance at runtime; you must still install the regular PHP code.
The C extension is only compatible and useful for **PHP5**.
Note that this extension does not replace the PHP code but only provides an
optimized version of the ``\Twig\Template::getAttribute()`` method; you must
still install the regular PHP code
Twig comes with a C extension that enhances the performance of the Twig
runtime engine; install it like any other PHP extensions:
The C extension is only compatible and useful for **PHP5**.
Install it like any other PHP extensions:
.. code-block:: bash
@@ -68,17 +37,6 @@ runtime engine; install it like any other PHP extensions:
make
make install
.. note::
You can also install the C extension via PEAR (note that this method is
deprecated and newer versions of Twig are not available on the PEAR
channel):
.. code-block:: bash
pear channel-discover pear.twig-project.org
pear install twig/CTwig
For Windows:
1. Setup the build environment following the `PHP documentation`_
@@ -103,13 +61,11 @@ Finally, enable the extension in your ``php.ini`` configuration file:
.. code-block:: ini
extension=twig.so #For Unix systems
extension=php_twig.dll #For Windows systems
extension=twig.so # For Unix systems
extension=php_twig.dll # For Windows systems
And from now 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.
advantage of the C extension.
.. _`download page`: https://github.com/twigphp/Twig/tags
.. _`Composer`: https://getcomposer.org/download/
+4 -2
View File
@@ -16,11 +16,13 @@ The rendering of a Twig template can be summarized into four key steps:
* First, the **lexer** tokenizes the template source code into small pieces
for easier processing;
* Then, the **parser** converts the token stream into a meaningful tree
of nodes (the Abstract Syntax Tree);
* Eventually, the *compiler* transforms the AST into PHP code.
* **Evaluate** the template: It basically means calling the ``display()``
* Finally, the *compiler* transforms the AST into PHP code.
* **Evaluate** the template: It means calling the ``display()``
method of the compiled template and passing it the context.
The Lexer
+8 -18
View File
@@ -1,13 +1,11 @@
Introduction
============
This is the documentation for Twig, the flexible, fast, and secure template
Welcome to the documentation for Twig, the flexible, fast, and secure template
engine for PHP.
If you have any exposure to other text-based template languages, such as
Smarty, Django, or Jinja, you should feel right at home with Twig. It's both
designer and developer friendly by sticking to PHP's principles and adding
functionality useful for templating environments.
Twig is both designer and developer friendly by sticking to PHP's principles and
adding functionality useful for templating environments.
The key-features are...
@@ -22,14 +20,13 @@ The key-features are...
developer to define their own custom tags and filters, and to create their own DSL.
Twig is used by many Open-Source projects like Symfony, Drupal8, eZPublish,
phpBB, Piwik, OroCRM; and many frameworks have support for it as well like
Slim, Yii, Laravel, Codeigniter and Kohana — just to name a few.
phpBB, Matomo, OroCRM; and many frameworks have support for it as well like
Slim, Yii, Laravel, and Codeigniter — just to name a few.
Prerequisites
-------------
Twig needs at least **PHP 5.2.7** to run. As of 1.34, the minimum requirement
was bumped to **PHP 5.3.3**.
Twig needs at least **PHP 5.4.0** to run.
Installation
------------
@@ -38,7 +35,7 @@ The recommended way to install Twig is via Composer:
.. code-block:: bash
composer require "twig/twig:~1.0"
composer require "twig/twig:^1.0"
.. note::
@@ -63,7 +60,7 @@ This section gives you a brief introduction to the PHP API for Twig.
echo $twig->render('index', ['name' => 'Fabien']);
Twig uses a loader (``\Twig\Loader\ArrayLoader``) to locate templates, and an
environment (``\Twig\Environment``) to store the configuration.
environment (``\Twig\Environment``) to store its configuration.
The ``render()`` method loads the template passed as a first argument and
renders it with the variables passed as a second argument.
@@ -77,10 +74,3 @@ filesystem loader::
]);
echo $twig->render('index.html', ['name' => 'Fabien']);
.. tip::
If you are not using Composer, use the Twig built-in autoloader::
require_once '/path/to/lib/Twig/Autoloader.php';
Twig_Autoloader::register();
+5 -5
View File
@@ -13,8 +13,8 @@ Deprecated features generate deprecation notices (via a call to the
``trigger_error()`` PHP function). By default, they are silenced and never
displayed nor logged.
To easily remove all deprecated feature usages from your templates, write and
run a script along the lines of the following::
To remove all deprecated feature usages from your templates, write and run a
script along the lines of the following::
require_once __DIR__.'/vendor/autoload.php';
@@ -57,7 +57,7 @@ they won't be generated when templates are already cached.
If you want to manage the deprecation notices from your PHPUnit tests, have
a look at the `symfony/phpunit-bridge
<https://github.com/symfony/phpunit-bridge>`_ package, which eases the
process a lot.
process.
Making a Layout conditional
---------------------------
@@ -155,7 +155,7 @@ parent's full, unambiguous template path in the extends tag:
Customizing the Syntax
----------------------
Twig allows some syntax customization for the block delimiters. It's not
Twig allows some syntax customization for the block delimiters. It's **not**
recommended to use this feature as templates will be tied with your custom
syntax. But for specific projects, it can make sense to change the defaults.
@@ -202,7 +202,7 @@ When Twig encounters a variable like ``article.title``, it tries to find a
``title`` public property in the ``article`` object.
It also works if the property does not exist but is rather defined dynamically
thanks to the magic ``__get()`` method; you just need to also implement the
thanks to the magic ``__get()`` method; you need to also implement the
``__isset()`` magic method like shown in the following snippet of code::
class Article
+51 -59
View File
@@ -7,13 +7,13 @@ will 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,
A template is a regular 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 with
values when the template is evaluated, and **tags**, which control the logic
of the template.
values when the template is evaluated, and **tags**, which control the
template's logic.
Below is a minimal template that illustrates a few basics. We will cover further
details later on:
@@ -38,8 +38,8 @@ details later on:
</html>
There are two kinds of delimiters: ``{% ... %}`` and ``{{ ... }}``. The first
one is used to execute statements such as for-loops, the latter prints the
result of an expression to the template.
one is used to execute statements such as for-loops, the latter outputs the
result of an expression.
IDEs Integration
----------------
@@ -68,27 +68,16 @@ Variables
---------
The application passes variables to the templates for manipulation in the
template. Variables may have attributes or elements you can access,
too. The visual representation of a variable depends heavily on the application providing
template. Variables may have attributes or elements you can access, too. The
visual representation of a variable depends heavily on the application providing
it.
You can use a dot (``.``) to access attributes of a variable (methods or
properties of a PHP object, or items of a PHP array), or the so-called
"subscript" syntax (``[]``):
Use a dot (``.``) to access attributes of a variable (methods or properties of a
PHP object, or items of a PHP array):
.. code-block:: twig
{{ foo.bar }}
{{ foo['bar'] }}
When the attribute contains special characters (like ``-`` that would be
interpreted as the minus operator), use the ``attribute`` function instead to
access the variable attribute:
.. code-block:: twig
{# equivalent to the non-working foo.data-foo #}
{{ attribute(foo, 'data-foo') }}
.. note::
@@ -96,10 +85,6 @@ access the variable attribute:
variable 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`` value
when the ``strict_variables`` option is set to ``false``; alternatively, if ``strict_variables``
is set, Twig will throw an error (see :ref:`environment options<environment_options>`).
.. sidebar:: Implementation
For convenience's sake ``foo.bar`` does the following things on the PHP
@@ -113,16 +98,30 @@ is set, Twig will throw an error (see :ref:`environment options<environment_opti
* 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:
Twig also supports a specific syntax for accessing items on PHP arrays,
``foo['bar']``:
* check if ``foo`` is an array and ``bar`` a valid element;
* if not, return a ``null`` value.
If a variable or attribute does not exist, you will receive a ``null`` value
when the ``strict_variables`` option is set to ``false``; alternatively, if ``strict_variables``
is set, Twig will throw an error (see :ref:`environment options<environment_options>`).
.. note::
If you want to access a dynamic attribute of a variable, use the
:doc:`attribute<functions/attribute>` function instead.
The ``attribute`` function is also useful when the attribute contains
special characters (like ``-`` that would be interpreted as the minus
operator):
.. code-block:: twig
{# equivalent to the non-working foo.data-foo #}
{{ attribute(foo, 'data-foo') }}
Global Variables
~~~~~~~~~~~~~~~~
@@ -148,9 +147,8 @@ Filters
-------
Variables can be modified by **filters**. Filters are separated from the
variable by a pipe symbol (``|``) and may have optional arguments in
parentheses. Multiple filters can be chained. The output of one filter is
applied to the next.
variable by a pipe symbol (``|``). Multiple filters can be chained. The output
of one filter is applied to the next.
The following example removes all HTML tags from the ``name`` and title-cases
it:
@@ -160,13 +158,13 @@ it:
{{ name|striptags|title }}
Filters that accept arguments have parentheses around the arguments. This
example will join a list by commas:
example joins the elements of a list by commas:
.. code-block:: twig
{{ list|join(', ') }}
To apply a filter on a section of code, wrap it in the
To apply a filter on a section of code, wrap it with the
:doc:`apply<tags/apply>` tag:
.. code-block:: twig
@@ -338,11 +336,10 @@ allows you to build a base "skeleton" template that contains all the common
elements of your site and defines **blocks** that child templates can
override.
Sounds complicated but it is very basic. It's easier to understand it by
starting with an example.
It's easier to understand the concept by starting with an example.
Let's define a base template, ``base.html``, which defines a simple HTML
skeleton document that you might use for a simple two-column page:
Let's define a base template, ``base.html``, which defines an HTML skeleton
document that might be used for a two-column page:
.. code-block:: html+twig
@@ -417,9 +414,8 @@ parent block:
.. note::
Twig also supports multiple inheritance with the so called horizontal reuse
with the help of the :doc:`use<tags/use>` tag. This is an advanced feature
hardly ever needed in regular templates.
Twig also supports multiple inheritance via "horizontal reuse" with the help
of the :doc:`use<tags/use>` tag.
HTML Escaping
-------------
@@ -437,19 +433,17 @@ The automatic escaping strategy can be configured via the
Working with Manual Escaping
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If manual escaping is enabled, it is **your** responsibility to escape
variables if needed. What to escape? Any variable you don't trust.
If manual escaping is enabled, it is **your** responsibility to escape variables
if needed. What to escape? Any variable that comes from an untrusted source.
Escaping works by piping the variable through the
:doc:`escape<filters/escape>` or ``e`` filter:
Escaping works by using the :doc:`escape<filters/escape>` or ``e`` filter:
.. code-block:: twig
{{ user.username|e }}
By default, the ``escape`` filter uses the ``html`` strategy, but depending on
the escaping context, you might want to explicitly use any other available
strategies:
the escaping context, you might want to explicitly use an other strategy:
.. code-block:: twig
@@ -557,8 +551,7 @@ special ``varargs`` variable as a list of values.
Expressions
-----------
Twig allows expressions everywhere. These work very similar to regular PHP and
even if you're not working with PHP you should feel comfortable with it.
Twig allows expressions everywhere.
.. note::
@@ -597,7 +590,7 @@ exist:
backslash (e.g. ``'c:\Program Files'``) escape it by doubling it
(e.g. ``'c:\\Program Files'``).
* ``42`` / ``42.23``: Integers and floating point numbers are created by just
* ``42`` / ``42.23``: Integers and floating point numbers are created by
writing the number down. If a dot is present the number is a float,
otherwise an integer.
@@ -637,15 +630,15 @@ Arrays and hashes can be nested:
.. tip::
Using double-quoted or single-quoted strings has no impact on performance
but string interpolation is only supported in double-quoted strings.
but :ref:`string interpolation <templates-string-interpolation>` is only
supported in double-quoted strings.
Math
~~~~
Twig allows you to calculate with values. This is rarely useful in templates
but exists for completeness' sake. The following operators are supported:
Twig allows you to do math in templates; the following operators are supported:
* ``+``: Adds two objects together (the operands are casted to numbers). ``{{
* ``+``: Adds two numbers together (the operands are casted to numbers). ``{{
1 + 1 }}`` is ``2``.
* ``-``: Subtracts the second number from the first one. ``{{ 3 - 2 }}`` is
@@ -720,9 +713,8 @@ string:
Containment Operator
~~~~~~~~~~~~~~~~~~~~
The ``in`` operator performs containment test.
It returns ``true`` if the left operand is contained in the right:
The ``in`` operator performs containment test. It returns ``true`` if the left
operand is contained in the right:
.. code-block:: twig
@@ -787,7 +779,7 @@ 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 :doc:`range<functions/range>` function):
(this is syntactic sugar for the :doc:`range<functions/range>` function):
.. code-block:: twig
@@ -807,7 +799,7 @@ The following operators don't fit into any of the other categories:
" ~ name ~ "!" }}`` would return (assuming ``name`` is ``'John'``) ``Hello
John!``.
* ``.``, ``[]``: Gets an attribute of an object.
* ``.``, ``[]``: Gets an attribute of a variable.
* ``?:``: The ternary operator:
@@ -826,6 +818,8 @@ The following operators don't fit into any of the other categories:
{# returns the value of foo if it is defined and not null, 'no' otherwise #}
{{ foo ?? 'no' }}
.. _templates-string-interpolation
String Interpolation
~~~~~~~~~~~~~~~~~~~~
@@ -916,10 +910,8 @@ the modifiers on one side of a tag or on both sides:
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`_.
Twig can be extended. If you are looking for new tags, filters, or functions,
have a look at the Twig official `extension repository`_.
If you want to create your own, read the :ref:`Creating an
Extension<creating_extensions>` chapter.