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:: .. note::
The first section of this chapter describes how to extend Twig easily. If The first section of this chapter describes how to extend Twig. If you want
you want to reuse your changes in different projects or if you want to to reuse your changes in different projects or if you want to share them
share them with others, you should then create an extension as described with others, you should then create an extension as described in the
in the following section. following section.
.. caution:: .. caution::
@@ -56,7 +56,7 @@ three main reasons:
{{ 'some text' ~ {% lipsum 40 %} ~ 'some more text' }} {{ 'some text' ~ {% lipsum 40 %} ~ 'some more text' }}
In fact, you rarely need to create tags; and that's good news because tags are 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*: Now, let's use a ``lipsum`` *filter*:
@@ -64,10 +64,9 @@ Now, let's use a ``lipsum`` *filter*:
{{ 40|lipsum }} {{ 40|lipsum }}
Again, it works, but it looks weird. A filter transforms the passed value to Again, it works. But a filter should transform the passed value to something
something else but here we use the value to indicate the number of words to else. Here, we use the value to indicate the number of words to generate (so,
generate (so, ``40`` is an argument of the filter, not the value we want to ``40`` is an argument of the filter, not the value we want to transform).
transform).
Next, let's use a ``lipsum`` *function*: 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) %} {% set lipsum = lipsum(40) %}
Last but not the least, you can also use a *global* object with a method able Lastly, you can also use a *global* object with a method able to generate lorem
to generate lorem ipsum text: ipsum text:
.. code-block:: twig .. code-block:: twig
@@ -99,13 +98,13 @@ Keep in mind the following when you want to extend Twig:
========== ========================== ========== ========================= ========== ========================== ========== =========================
What? Implementation difficulty? How often? When? What? Implementation difficulty? How often? When?
========== ========================== ========== ========================= ========== ========================== ========== =========================
*macro* trivial frequent Content generation *macro* simple frequent Content generation
*global* trivial frequent Helper object *global* simple frequent Helper object
*function* trivial frequent Content generation *function* simple frequent Content generation
*filter* trivial frequent Value transformation *filter* simple frequent Value transformation
*tag* complex rare DSL language construct *tag* complex rare DSL language construct
*test* trivial rare Boolean decision *test* simple rare Boolean decision
*operator* trivial rare Values transformation *operator* simple rare Values transformation
========== ========================== ========== ========================= ========== ========================== ========== =========================
Globals Globals
@@ -126,7 +125,7 @@ You can then use the ``text`` variable anywhere in a template:
Filters 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 // an anonymous function
$filter = new \Twig\TwigFilter('rot13', function ($string) { $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 of the filter you will use in templates and the second one is the PHP callable
to associate with it. 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 = new \Twig\Environment($loader);
$twig->addFilter($filter); $twig->addFilter($filter);
@@ -251,14 +250,14 @@ option array.
Dynamic Filters Dynamic Filters
~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~
A filter name containing the special ``*`` character is a dynamic filter as A filter name containing the special ``*`` character is a dynamic filter and
the ``*`` can be any string:: the ``*`` part will match any string::
$filter = new \Twig\TwigFilter('*_path', function ($name, $arguments) { $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`` * ``product_path``
* ``category_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 The filter receives all dynamic part values before the normal filter arguments,
arguments, but after the environment and the context. For instance, a call to 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 ``'foo'|a_path_b()`` will result in the following arguments to be passed to the
the filter: ``('a', 'b', 'foo')``. filter: ``('a', 'b', 'foo')``.
Deprecated Filters Deprecated Filters
~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~
@@ -334,7 +333,7 @@ objects are 'red'::
}); });
$twig->addTest($test); $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 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. 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 The above example shows how you can create tests that use a node class. The node
node class has access to one sub-node called 'node'. This sub-node contains the 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: value that is being tested. When the ``odd`` filter is used in code such as:
.. code-block:: twig .. 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 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 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 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! 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 Let's create a ``set`` tag that allows the definition of simple variables from
variables from within a template. The tag can be used like follows: within a template. The tag can be used like follows:
.. code-block:: twig .. 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 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 available. The built-in version is slightly more powerful and supports
multiple assignments by default (cf. the template designers chapter for multiple assignments by default.
more information).
Three steps are needed to define a new tag: 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 Registering a new tag
~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~
Adding a tag is as simple as calling the ``addTokenParser`` method on the Add a tag by calling the ``addTokenParser`` method on the ``\Twig\Environment``
``\Twig\Environment`` instance:: instance::
$twig = new \Twig\Environment($loader); $twig = new \Twig\Environment($loader);
$twig->addTokenParser(new Project_Set_TokenParser()); $twig->addTokenParser(new Project_Set_TokenParser());
@@ -524,7 +522,7 @@ the ``set`` tag.
Defining a Node 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 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 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 reusable class like adding support for internationalization. An extension can
define tags, filters, tests, operators, global variables, functions, and node define tags, filters, tests, operators, functions, and node visitors.
visitors.
Most of the time, it is useful to create a single extension for your project, 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. 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 This extension does nothing for now. We will customize it in the next sections.
next sections.
.. note:: .. note::
Prior to Twig 1.26, you must implement the ``getName()`` method which must Prior to Twig 1.26, you must implement the ``getName()`` method which must
return a unique identifier for the extension. return a unique identifier for the extension.
Twig does not care where you save your extension on the filesystem, as all You can save your extension anywhere on the filesystem, as all extensions must
extensions must be registered explicitly to be available in your templates. be registered explicitly to be available in your templates.
You can register an extension by using the ``addExtension()`` method on your You can register an extension by using the ``addExtension()`` method on your
main ``Environment`` object:: main ``Environment`` object::
@@ -775,7 +771,7 @@ Operators
~~~~~~~~~ ~~~~~~~~~
The ``getOperators()`` methods lets you add new operators. Here is how to add 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 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:: .. note::
As of Twig 1.32, Twig comes with a PSR-11 compatible runtime loader 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 It is now possible to move the runtime logic to a new
``Project_Twig_RuntimeExtension`` class and use it directly in the extension:: ``Project_Twig_RuntimeExtension`` class and use it directly in the extension::
@@ -961,8 +957,8 @@ Testing an Extension
Functional Tests Functional Tests
~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~
You can create functional tests for extensions simply by creating the You can create functional tests for extensions by creating the following file
following file structure in your test directory:: structure in your test directory::
Fixtures/ Fixtures/
filters/ filters/
+48 -42
View File
@@ -10,16 +10,14 @@ Basics
Twig uses a central object called the **environment** (of class Twig uses a central object called the **environment** (of class
``\Twig\Environment``). Instances of this class are used to store the ``\Twig\Environment``). Instances of this class are used to store the
configuration and extensions, and are used to load templates from the file configuration and extensions, and are used to load templates.
system or other locations.
Most applications will create one ``\Twig\Environment`` object on application Most applications create one ``\Twig\Environment`` object on application
initialization and use that to load templates. In some cases it's however initialization and use that to load templates. In some cases, it might be useful
useful to have multiple environments side by side, if different configurations to have multiple environments side by side, with different configurations.
are in use.
The simplest way to configure Twig to load templates for your application The typical way to configure Twig to load templates for an application looks
looks roughly like this:: roughly like this::
require_once '/path/to/lib/Twig/Autoloader.php'; require_once '/path/to/lib/Twig/Autoloader.php';
Twig_Autoloader::register(); Twig_Autoloader::register();
@@ -29,8 +27,8 @@ looks roughly like this::
'cache' => '/path/to/compilation_cache', 'cache' => '/path/to/compilation_cache',
]); ]);
This will create a template environment with the default settings and a loader This creates a template environment with a default configuration and a loader
that looks up the templates in the ``/path/to/templates/`` folder. Different 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 loaders are available and you can also write your own if you want to load
templates from a database or other resources. templates from a database or other resources.
@@ -53,7 +51,7 @@ returns a ``\Twig\TemplateWrapper`` instance::
.. note:: .. 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. ``\Twig\Template`` instance.
To render the template with some variables, call the ``render()`` method:: 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:: .. 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:: 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 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 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. the performance boost is even larger if you use a PHP accelerator such as
See the ``cache`` and ``auto_reload`` options of ``\Twig\Environment`` above OPCache. See the ``cache`` and ``auto_reload`` options of ``\Twig\Environment``
for more information. above for more information.
Built-in Loaders 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`` ``\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``
............................ ............................
``\Twig\Loader\ArrayLoader`` loads a template from a PHP array. It's passed an array ``\Twig\Loader\ArrayLoader`` loads a template from a PHP array. It is passed an
of strings bound to template names:: array of strings bound to template names::
$loader = new \Twig\Loader\ArrayLoader([ $loader = new \Twig\Loader\ArrayLoader([
'index.html' => 'Hello {{ name }}!', 'index.html' => 'Hello {{ name }}!',
@@ -239,11 +237,11 @@ projects where storing all templates in a single PHP file might make sense.
.. tip:: .. tip::
When using the ``Array`` or ``String`` loaders with a cache mechanism, you When using the ``Array``loaders with a cache mechanism, you should know that
should know that a new cache key is generated each time a template content a new cache key is generated each time a template content "changes" (the
"changes" (the cache key being the source code of the template). If you cache key being the source code of the template). If you don't want to see
don't want to see your cache grows out of control, you need to take care your cache grows out of control, you need to take care of clearing the old
of clearing the old cache file by yourself. cache file by yourself.
``\Twig\Loader\ChainLoader`` ``\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); $twig = new \Twig\Environment($loader);
When looking for a template, Twig will try each loader in turn and it will When looking for a template, Twig tries each loader in turn and returns as soon
return as soon as the template is found. When rendering the ``index.html`` as the template is found. When rendering the ``index.html`` template from the
template from the above example, Twig will load it with ``$loader2`` but the above example, Twig will load it with ``$loader2`` but the ``base.html``
``base.html`` template will be loaded from ``$loader1``. template will be loaded from ``$loader1``.
``\Twig\Loader\ChainLoader`` accepts any loader that implements
``\Twig\Loader\LoaderInterface``.
.. note:: .. note::
@@ -326,28 +321,34 @@ is still fresh, given the last modification time, or ``false`` otherwise.
Using Extensions Using Extensions
---------------- ----------------
Twig extensions are packages that add new features to Twig. Using an Twig extensions are packages that add new features to Twig. Register an
extension is as simple as using the ``addExtension()`` method:: extension via the ``addExtension()`` method::
$twig->addExtension(new \Twig\Extension\SandboxExtension()); $twig->addExtension(new \Twig\Extension\SandboxExtension());
Twig comes bundled with the following extensions: 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 * *Twig\Extension\DebugExtension*: Defines the ``dump`` function to help debug
to escape/unescape blocks of code. 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. environment, making it safe to evaluate untrusted code.
* *Twig_Extension_Profiler*: Enabled the built-in Twig profiler (as of Twig * *Twig\Extension\ProfilerExtension*: Enabled the built-in Twig profiler (as of
1.18). 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\Extension\StringLoaderExtension*: Defined the ``template_from_string``
Twig environment, as they are registered by default. function to allow loading templates from string in a template.
The Core, Escaper, and Optimizer extensions are registered by default.
Built-in Extensions Built-in Extensions
------------------- -------------------
@@ -537,7 +538,8 @@ compatible format::
file_put_contents('/path/to/profile.prof', $dumper->dump($profile)); file_put_contents('/path/to/profile.prof', $dumper->dump($profile));
Upload the profile to visualize it (create a `free account 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 .. code-block:: sh
@@ -561,13 +563,17 @@ Twig supports the following optimizations:
* ``\Twig\NodeVisitor\OptimizerNodeVisitor::OPTIMIZE_ALL``, enables all optimizations * ``\Twig\NodeVisitor\OptimizerNodeVisitor::OPTIMIZE_ALL``, enables all optimizations
(this is the default value). (this is the default value).
* ``\Twig\NodeVisitor\OptimizerNodeVisitor::OPTIMIZE_NONE``, disables all optimizations. * ``\Twig\NodeVisitor\OptimizerNodeVisitor::OPTIMIZE_NONE``, disables all optimizations.
This reduces the compilation time, but it can increase the execution time This reduces the compilation time, but it can increase the execution time
and the consumed memory. and the consumed memory.
* ``\Twig\NodeVisitor\OptimizerNodeVisitor::OPTIMIZE_FOR``, optimizes the ``for`` tag by * ``\Twig\NodeVisitor\OptimizerNodeVisitor::OPTIMIZE_FOR``, optimizes the ``for`` tag by
removing the ``loop`` variable creation whenever possible. removing the ``loop`` variable creation whenever possible.
* ``\Twig\NodeVisitor\OptimizerNodeVisitor::OPTIMIZE_RAW_FILTER``, removes the ``raw`` * ``\Twig\NodeVisitor\OptimizerNodeVisitor::OPTIMIZE_RAW_FILTER``, removes the ``raw``
filter whenever possible. filter whenever possible.
* ``\Twig\NodeVisitor\OptimizerNodeVisitor::OPTIMIZE_VAR_ACCESS``, simplifies the creation * ``\Twig\NodeVisitor\OptimizerNodeVisitor::OPTIMIZE_VAR_ACCESS``, simplifies the creation
and access of variables in the compiled templates whenever possible. 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 the Twig PHP package
------------------------------- -------------------------------
Installing via Composer (recommended) Install `Composer`_ and run the following command:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Install `Composer`_ and run the following command to get the latest version:
.. code-block:: bash .. code-block:: bash
composer require twig/twig:~1.0 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
Installing the C extension Installing the C extension
-------------------------- --------------------------
@@ -49,16 +18,16 @@ Installing the C extension
.. versionadded:: 1.4 .. versionadded:: 1.4
The C extension was added in Twig 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 Note that this extension does not replace the PHP code but only provides an
improvements. Note that the extension is not a replacement for the PHP optimized version of the ``\Twig\Template::getAttribute()`` method; you must
code; it only implements a small part of the PHP code to improve the still install the regular PHP code
performance at runtime; you must still install the regular PHP code.
The C extension is only compatible and useful for **PHP5**.
Twig comes with a C extension that enhances the performance of the Twig The C extension is only compatible and useful for **PHP5**.
runtime engine; install it like any other PHP extensions:
Install it like any other PHP extensions:
.. code-block:: bash .. code-block:: bash
@@ -68,17 +37,6 @@ runtime engine; install it like any other PHP extensions:
make make
make install 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: For Windows:
1. Setup the build environment following the `PHP documentation`_ 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 .. code-block:: ini
extension=twig.so #For Unix systems extension=twig.so # For Unix systems
extension=php_twig.dll #For Windows systems extension=php_twig.dll # For Windows systems
And from now on, Twig will automatically compile your templates to take 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 advantage of the C extension.
PHP code but only provides an optimized version of the
``\Twig\Template::getAttribute()`` method.
.. _`download page`: https://github.com/twigphp/Twig/tags .. _`download page`: https://github.com/twigphp/Twig/tags
.. _`Composer`: https://getcomposer.org/download/ .. _`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 * First, the **lexer** tokenizes the template source code into small pieces
for easier processing; for easier processing;
* Then, the **parser** converts the token stream into a meaningful tree * Then, the **parser** converts the token stream into a meaningful tree
of nodes (the Abstract Syntax 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. method of the compiled template and passing it the context.
The Lexer The Lexer
+8 -18
View File
@@ -1,13 +1,11 @@
Introduction 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. engine for PHP.
If you have any exposure to other text-based template languages, such as Twig is both designer and developer friendly by sticking to PHP's principles and
Smarty, Django, or Jinja, you should feel right at home with Twig. It's both adding functionality useful for templating environments.
designer and developer friendly by sticking to PHP's principles and adding
functionality useful for templating environments.
The key-features are... 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. 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, 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 phpBB, Matomo, OroCRM; and many frameworks have support for it as well like
Slim, Yii, Laravel, Codeigniter and Kohana — just to name a few. Slim, Yii, Laravel, and Codeigniter — just to name a few.
Prerequisites Prerequisites
------------- -------------
Twig needs at least **PHP 5.2.7** to run. As of 1.34, the minimum requirement Twig needs at least **PHP 5.4.0** to run.
was bumped to **PHP 5.3.3**.
Installation Installation
------------ ------------
@@ -38,7 +35,7 @@ The recommended way to install Twig is via Composer:
.. code-block:: bash .. code-block:: bash
composer require "twig/twig:~1.0" composer require "twig/twig:^1.0"
.. note:: .. note::
@@ -63,7 +60,7 @@ This section gives you a brief introduction to the PHP API for Twig.
echo $twig->render('index', ['name' => 'Fabien']); echo $twig->render('index', ['name' => 'Fabien']);
Twig uses a loader (``\Twig\Loader\ArrayLoader``) to locate templates, and an 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 The ``render()`` method loads the template passed as a first argument and
renders it with the variables passed as a second argument. renders it with the variables passed as a second argument.
@@ -77,10 +74,3 @@ filesystem loader::
]); ]);
echo $twig->render('index.html', ['name' => 'Fabien']); 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 ``trigger_error()`` PHP function). By default, they are silenced and never
displayed nor logged. displayed nor logged.
To easily remove all deprecated feature usages from your templates, write and To remove all deprecated feature usages from your templates, write and run a
run a script along the lines of the following:: script along the lines of the following::
require_once __DIR__.'/vendor/autoload.php'; 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 If you want to manage the deprecation notices from your PHPUnit tests, have
a look at the `symfony/phpunit-bridge a look at the `symfony/phpunit-bridge
<https://github.com/symfony/phpunit-bridge>`_ package, which eases the <https://github.com/symfony/phpunit-bridge>`_ package, which eases the
process a lot. process.
Making a Layout conditional Making a Layout conditional
--------------------------- ---------------------------
@@ -155,7 +155,7 @@ parent's full, unambiguous template path in the extends tag:
Customizing the Syntax 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 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. 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. ``title`` public property in the ``article`` object.
It also works if the property does not exist but is rather defined dynamically 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:: ``__isset()`` magic method like shown in the following snippet of code::
class Article class Article
+51 -59
View File
@@ -7,13 +7,13 @@ will be most useful as reference to those creating Twig templates.
Synopsis 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, CSV, LaTeX, etc.). It doesn't have a specific extension, ``.html`` or
``.xml`` are just fine. ``.xml`` are just fine.
A template contains **variables** or **expressions**, which get replaced with A template contains **variables** or **expressions**, which get replaced with
values when the template is evaluated, and **tags**, which control the logic values when the template is evaluated, and **tags**, which control the
of the template. template's logic.
Below is a minimal template that illustrates a few basics. We will cover further Below is a minimal template that illustrates a few basics. We will cover further
details later on: details later on:
@@ -38,8 +38,8 @@ details later on:
</html> </html>
There are two kinds of delimiters: ``{% ... %}`` and ``{{ ... }}``. The first There are two kinds of delimiters: ``{% ... %}`` and ``{{ ... }}``. The first
one is used to execute statements such as for-loops, the latter prints the one is used to execute statements such as for-loops, the latter outputs the
result of an expression to the template. result of an expression.
IDEs Integration IDEs Integration
---------------- ----------------
@@ -68,27 +68,16 @@ Variables
--------- ---------
The application passes variables to the templates for manipulation in the The application passes variables to the templates for manipulation in the
template. Variables may have attributes or elements you can access, template. Variables may have attributes or elements you can access, too. The
too. The visual representation of a variable depends heavily on the application providing visual representation of a variable depends heavily on the application providing
it. it.
You can use a dot (``.``) to access attributes of a variable (methods or Use a dot (``.``) to access attributes of a variable (methods or properties of a
properties of a PHP object, or items of a PHP array), or the so-called PHP object, or items of a PHP array):
"subscript" syntax (``[]``):
.. code-block:: twig .. code-block:: twig
{{ foo.bar }} {{ 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:: .. note::
@@ -96,10 +85,6 @@ access the variable attribute:
variable but the print statement. When accessing variables inside tags, variable but the print statement. When accessing variables inside tags,
don't put the braces around them. 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 .. sidebar:: Implementation
For convenience's sake ``foo.bar`` does the following things on the PHP 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, and if ``foo`` is an object, check that ``isBar`` is a valid method;
* if not, return a ``null`` value. * 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; * check if ``foo`` is an array and ``bar`` a valid element;
* if not, return a ``null`` value. * 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:: .. note::
If you want to access a dynamic attribute of a variable, use the If you want to access a dynamic attribute of a variable, use the
:doc:`attribute<functions/attribute>` function instead. :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 Global Variables
~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~
@@ -148,9 +147,8 @@ Filters
------- -------
Variables can be modified by **filters**. Filters are separated from the Variables can be modified by **filters**. Filters are separated from the
variable by a pipe symbol (``|``) and may have optional arguments in variable by a pipe symbol (``|``). Multiple filters can be chained. The output
parentheses. Multiple filters can be chained. The output of one filter is of one filter is applied to the next.
applied to the next.
The following example removes all HTML tags from the ``name`` and title-cases The following example removes all HTML tags from the ``name`` and title-cases
it: it:
@@ -160,13 +158,13 @@ it:
{{ name|striptags|title }} {{ name|striptags|title }}
Filters that accept arguments have parentheses around the arguments. This 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 .. code-block:: twig
{{ list|join(', ') }} {{ 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: :doc:`apply<tags/apply>` tag:
.. code-block:: twig .. 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 elements of your site and defines **blocks** that child templates can
override. override.
Sounds complicated but it is very basic. It's easier to understand it by It's easier to understand the concept by starting with an example.
starting with an example.
Let's define a base template, ``base.html``, which defines a simple HTML Let's define a base template, ``base.html``, which defines an HTML skeleton
skeleton document that you might use for a simple two-column page: document that might be used for a two-column page:
.. code-block:: html+twig .. code-block:: html+twig
@@ -417,9 +414,8 @@ parent block:
.. note:: .. note::
Twig also supports multiple inheritance with the so called horizontal reuse Twig also supports multiple inheritance via "horizontal reuse" with the help
with the help of the :doc:`use<tags/use>` tag. This is an advanced feature of the :doc:`use<tags/use>` tag.
hardly ever needed in regular templates.
HTML Escaping HTML Escaping
------------- -------------
@@ -437,19 +433,17 @@ The automatic escaping strategy can be configured via the
Working with Manual Escaping Working with Manual Escaping
~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If manual escaping is enabled, it is **your** responsibility to escape If manual escaping is enabled, it is **your** responsibility to escape variables
variables if needed. What to escape? Any variable you don't trust. if needed. What to escape? Any variable that comes from an untrusted source.
Escaping works by piping the variable through the Escaping works by using the :doc:`escape<filters/escape>` or ``e`` filter:
:doc:`escape<filters/escape>` or ``e`` filter:
.. code-block:: twig .. code-block:: twig
{{ user.username|e }} {{ user.username|e }}
By default, the ``escape`` filter uses the ``html`` strategy, but depending on By default, the ``escape`` filter uses the ``html`` strategy, but depending on
the escaping context, you might want to explicitly use any other available the escaping context, you might want to explicitly use an other strategy:
strategies:
.. code-block:: twig .. code-block:: twig
@@ -557,8 +551,7 @@ special ``varargs`` variable as a list of values.
Expressions Expressions
----------- -----------
Twig allows expressions everywhere. These work very similar to regular PHP and Twig allows expressions everywhere.
even if you're not working with PHP you should feel comfortable with it.
.. note:: .. note::
@@ -597,7 +590,7 @@ exist:
backslash (e.g. ``'c:\Program Files'``) escape it by doubling it backslash (e.g. ``'c:\Program Files'``) escape it by doubling it
(e.g. ``'c:\\Program Files'``). (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, writing the number down. If a dot is present the number is a float,
otherwise an integer. otherwise an integer.
@@ -637,15 +630,15 @@ Arrays and hashes can be nested:
.. tip:: .. tip::
Using double-quoted or single-quoted strings has no impact on performance 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 Math
~~~~ ~~~~
Twig allows you to calculate with values. This is rarely useful in templates Twig allows you to do math in templates; the following operators are supported:
but exists for completeness' sake. 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``. 1 + 1 }}`` is ``2``.
* ``-``: Subtracts the second number from the first one. ``{{ 3 - 2 }}`` is * ``-``: Subtracts the second number from the first one. ``{{ 3 - 2 }}`` is
@@ -720,9 +713,8 @@ string:
Containment Operator Containment Operator
~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~
The ``in`` operator performs containment test. The ``in`` operator performs containment test. It returns ``true`` if the left
operand is contained in the right:
It returns ``true`` if the left operand is contained in the right:
.. code-block:: twig .. code-block:: twig
@@ -787,7 +779,7 @@ The following operators don't fit into any of the other categories:
* ``|``: Applies a filter. * ``|``: Applies a filter.
* ``..``: Creates a sequence based on the operand before and after the operator * ``..``: 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 .. 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 " ~ name ~ "!" }}`` would return (assuming ``name`` is ``'John'``) ``Hello
John!``. John!``.
* ``.``, ``[]``: Gets an attribute of an object. * ``.``, ``[]``: Gets an attribute of a variable.
* ``?:``: The ternary operator: * ``?:``: 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 #} {# returns the value of foo if it is defined and not null, 'no' otherwise #}
{{ foo ?? 'no' }} {{ foo ?? 'no' }}
.. _templates-string-interpolation
String Interpolation String Interpolation
~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~
@@ -916,10 +910,8 @@ the modifiers on one side of a tag or on both sides:
Extensions Extensions
---------- ----------
Twig can be easily extended. 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 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 If you want to create your own, read the :ref:`Creating an
Extension<creating_extensions>` chapter. Extension<creating_extensions>` chapter.