mirror of
https://github.com/twigphp/Twig.git
synced 2026-08-30 12:06:56 +00:00
Merge branch '2.x' into 3.x
* 2.x: tweaked the doc
This commit is contained in:
+42
-46
@@ -7,10 +7,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::
|
||||
|
||||
@@ -50,7 +50,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*:
|
||||
|
||||
@@ -58,10 +58,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*:
|
||||
|
||||
@@ -78,8 +77,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
|
||||
|
||||
@@ -93,13 +92,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
|
||||
@@ -120,7 +119,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) {
|
||||
@@ -143,7 +142,7 @@ The first argument passed to the ``\Twig\TwigFilter`` constructor is the name of
|
||||
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);
|
||||
@@ -241,14 +240,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``
|
||||
@@ -259,10 +258,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
|
||||
~~~~~~~~~~~~~~~~~~
|
||||
@@ -321,7 +320,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.
|
||||
@@ -347,8 +346,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
|
||||
@@ -361,7 +360,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
|
||||
----
|
||||
@@ -408,8 +407,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
|
||||
|
||||
@@ -423,8 +422,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:
|
||||
|
||||
@@ -437,8 +435,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());
|
||||
@@ -503,7 +501,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
|
||||
{
|
||||
@@ -554,8 +552,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.
|
||||
@@ -626,11 +623,10 @@ 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.
|
||||
|
||||
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::
|
||||
@@ -722,7 +718,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
|
||||
{
|
||||
@@ -908,8 +904,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/
|
||||
|
||||
+46
-40
@@ -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/vendor/autoload.php';
|
||||
|
||||
@@ -28,8 +26,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.
|
||||
|
||||
@@ -56,7 +54,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::
|
||||
|
||||
@@ -136,14 +134,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``
|
||||
.................................
|
||||
@@ -197,8 +195,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 }}!',
|
||||
@@ -212,11 +210,11 @@ projects where storing all templates in a single PHP file might make sense.
|
||||
|
||||
.. tip::
|
||||
|
||||
When using the ``Array`` loader 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`` loader 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``
|
||||
............................
|
||||
@@ -235,13 +233,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::
|
||||
|
||||
@@ -306,27 +301,33 @@ The ``getSourceContext()`` method must return an instance of ``\Twig\Source``.
|
||||
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.
|
||||
* *Twig\Extension\ProfilerExtension*: Enabled the built-in Twig profiler.
|
||||
|
||||
* *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
|
||||
-------------------
|
||||
@@ -511,7 +512,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
|
||||
|
||||
@@ -535,13 +537,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.
|
||||
|
||||
|
||||
+4
-2
@@ -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
|
||||
|
||||
+6
-8
@@ -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,8 +20,8 @@ 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
|
||||
-------------
|
||||
@@ -56,7 +54,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.
|
||||
|
||||
+5
-5
@@ -10,8 +10,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';
|
||||
|
||||
@@ -54,7 +54,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
|
||||
---------------------------
|
||||
@@ -152,7 +152,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.
|
||||
|
||||
@@ -199,7 +199,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
@@ -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
|
||||
@@ -114,16 +99,30 @@ is set, Twig will throw an error (see :ref:`environment options<environment_opti
|
||||
* if not, and if ``foo`` is an object, check that ``hasBar`` 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
|
||||
~~~~~~~~~~~~~~~~
|
||||
|
||||
@@ -149,9 +148,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:
|
||||
@@ -161,13 +159,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
|
||||
@@ -331,11 +329,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
|
||||
|
||||
@@ -410,9 +407,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
|
||||
-------------
|
||||
@@ -430,19 +426,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
|
||||
|
||||
@@ -547,8 +541,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::
|
||||
|
||||
@@ -584,7 +577,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.
|
||||
|
||||
@@ -624,15 +617,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
|
||||
@@ -707,9 +700,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
|
||||
|
||||
@@ -771,7 +763,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
|
||||
|
||||
@@ -791,7 +783,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:
|
||||
|
||||
@@ -808,6 +800,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
|
||||
~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
@@ -889,10 +883,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.
|
||||
|
||||
Reference in New Issue
Block a user