mirror of
https://github.com/twigphp/Twig.git
synced 2026-08-30 20:16:45 +00:00
removed obsolete docs
This commit is contained in:
@@ -1,12 +1,6 @@
|
||||
Extending Twig
|
||||
==============
|
||||
|
||||
.. caution::
|
||||
|
||||
This section describes how to extend Twig as of **Twig 1.12**. If you are
|
||||
using an older version, read the :doc:`legacy<advanced_legacy>` chapter
|
||||
instead.
|
||||
|
||||
Twig can be extended in many ways; you can add extra tags, filters, tests,
|
||||
operators, global variables, and functions. You can even extend the parser
|
||||
itself with node visitors.
|
||||
@@ -126,11 +120,6 @@ You can then use the ``text`` variable anywhere in a template:
|
||||
Filters
|
||||
-------
|
||||
|
||||
.. caution::
|
||||
|
||||
The class to create a filter is ``Twig_SimpleFilter`` in Twig 1.x, but
|
||||
``Twig_Filter`` in Twig 2.x.
|
||||
|
||||
Creating a filter is as simple as associating a name with a PHP callable::
|
||||
|
||||
// an anonymous function
|
||||
@@ -257,11 +246,6 @@ the filter: ``('a', 'b', 'foo')``.
|
||||
Functions
|
||||
---------
|
||||
|
||||
.. caution::
|
||||
|
||||
The class to create a function is ``Twig_SimpleFunction`` in Twig 1.x, but
|
||||
``Twig_Function`` in Twig 2.x.
|
||||
|
||||
Functions are defined in the exact same way as filters, but you need to create
|
||||
an instance of ``Twig_Function``::
|
||||
|
||||
@@ -277,11 +261,6 @@ and ``preserves_safety`` options.
|
||||
Tests
|
||||
-----
|
||||
|
||||
.. caution::
|
||||
|
||||
The class to create a test is ``Twig_SimpleTest`` in Twig 1.x, but
|
||||
``Twig_Test`` in Twig 2.x.
|
||||
|
||||
Tests are defined in the exact same way as filters and functions, but you need
|
||||
to create an instance of ``Twig_Test``::
|
||||
|
||||
|
||||
@@ -1,887 +0,0 @@
|
||||
Extending Twig
|
||||
==============
|
||||
|
||||
.. caution::
|
||||
|
||||
This section describes how to extends Twig for versions **older than
|
||||
1.12**. If you are using a newer version, read the :doc:`newer<advanced>`
|
||||
chapter instead.
|
||||
|
||||
Twig can be extended in many ways; you can add extra tags, filters, tests,
|
||||
operators, global variables, and functions. You can even extend the parser
|
||||
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.
|
||||
|
||||
.. caution::
|
||||
|
||||
When extending Twig by calling methods on the Twig environment instance,
|
||||
Twig won't be able to recompile your templates when the PHP code is
|
||||
updated. To see your changes in real-time, either disable template caching
|
||||
or package your code into an extension (see the next section of this
|
||||
chapter).
|
||||
|
||||
Before extending Twig, you must understand the differences between all the
|
||||
different possible extension points and when to use them.
|
||||
|
||||
First, remember that Twig has two main language constructs:
|
||||
|
||||
* ``{{ }}``: used to print the result of an expression evaluation;
|
||||
|
||||
* ``{% %}``: used to execute statements.
|
||||
|
||||
To understand why Twig exposes so many extension points, let's see how to
|
||||
implement a *Lorem ipsum* generator (it needs to know the number of words to
|
||||
generate).
|
||||
|
||||
You can use a ``lipsum`` *tag*:
|
||||
|
||||
.. code-block:: jinja
|
||||
|
||||
{% lipsum 40 %}
|
||||
|
||||
That works, but using a tag for ``lipsum`` is not a good idea for at least
|
||||
three main reasons:
|
||||
|
||||
* ``lipsum`` is not a language construct;
|
||||
* The tag outputs something;
|
||||
* The tag is not flexible as you cannot use it in an expression:
|
||||
|
||||
.. code-block:: jinja
|
||||
|
||||
{{ '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.
|
||||
|
||||
Now, let's use a ``lipsum`` *filter*:
|
||||
|
||||
.. code-block:: jinja
|
||||
|
||||
{{ 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).
|
||||
|
||||
Next, let's use a ``lipsum`` *function*:
|
||||
|
||||
.. code-block:: jinja
|
||||
|
||||
{{ lipsum(40) }}
|
||||
|
||||
Here we go. For this specific example, the creation of a function is the
|
||||
extension point to use. And you can use it anywhere an expression is accepted:
|
||||
|
||||
.. code-block:: jinja
|
||||
|
||||
{{ 'some text' ~ ipsum(40) ~ 'some more text' }}
|
||||
|
||||
{% set ipsum = ipsum(40) %}
|
||||
|
||||
Last but not the least, you can also use a *global* object with a method able
|
||||
to generate lorem ipsum text:
|
||||
|
||||
.. code-block:: jinja
|
||||
|
||||
{{ text.lipsum(40) }}
|
||||
|
||||
As a rule of thumb, use functions for frequently used features and global
|
||||
objects for everything else.
|
||||
|
||||
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
|
||||
*tag* complex rare DSL language construct
|
||||
*test* trivial rare Boolean decision
|
||||
*operator* trivial rare Values transformation
|
||||
========== ========================== ========== =========================
|
||||
|
||||
Globals
|
||||
-------
|
||||
|
||||
A global variable is like any other template variable, except that it's
|
||||
available in all templates and macros::
|
||||
|
||||
$twig = new Twig_Environment($loader);
|
||||
$twig->addGlobal('text', new Text());
|
||||
|
||||
You can then use the ``text`` variable anywhere in a template:
|
||||
|
||||
.. code-block:: jinja
|
||||
|
||||
{{ text.lipsum(40) }}
|
||||
|
||||
Filters
|
||||
-------
|
||||
|
||||
A filter is a regular PHP function or an object method that takes the left
|
||||
side of the filter (before the pipe ``|``) as first argument and the extra
|
||||
arguments passed to the filter (within parentheses ``()``) as extra arguments.
|
||||
|
||||
Defining a filter is as easy as associating the filter name with a PHP
|
||||
callable. For instance, let's say you have the following code in a template:
|
||||
|
||||
.. code-block:: jinja
|
||||
|
||||
{{ 'TWIG'|lower }}
|
||||
|
||||
When compiling this template to PHP, Twig looks for the PHP callable
|
||||
associated with the ``lower`` filter. The ``lower`` filter is a built-in Twig
|
||||
filter, and it is simply mapped to the PHP ``strtolower()`` function. After
|
||||
compilation, the generated PHP code is roughly equivalent to:
|
||||
|
||||
.. code-block:: html+php
|
||||
|
||||
<?php echo strtolower('TWIG') ?>
|
||||
|
||||
As you can see, the ``'TWIG'`` string is passed as a first argument to the PHP
|
||||
function.
|
||||
|
||||
A filter can also take extra arguments like in the following example:
|
||||
|
||||
.. code-block:: jinja
|
||||
|
||||
{{ now|date('d/m/Y') }}
|
||||
|
||||
In this case, the extra arguments are passed to the function after the main
|
||||
argument, and the compiled code is equivalent to:
|
||||
|
||||
.. code-block:: html+php
|
||||
|
||||
<?php echo twig_date_format_filter($now, 'd/m/Y') ?>
|
||||
|
||||
Let's see how to create a new filter.
|
||||
|
||||
In this section, we will create a ``rot13`` filter, which should return the
|
||||
`rot13`_ transformation of a string. Here is an example of its usage and the
|
||||
expected output:
|
||||
|
||||
.. code-block:: jinja
|
||||
|
||||
{{ "Twig"|rot13 }}
|
||||
|
||||
{# should displays Gjvt #}
|
||||
|
||||
Adding a filter is as simple as calling the ``addFilter()`` method on the
|
||||
``Twig_Environment`` instance::
|
||||
|
||||
$twig = new Twig_Environment($loader);
|
||||
$twig->addFilter('rot13', new Twig_Filter_Function('str_rot13'));
|
||||
|
||||
The second argument of ``addFilter()`` is an instance of ``Twig_Filter``.
|
||||
Here, we use ``Twig_Filter_Function`` as the filter is a PHP function. The
|
||||
first argument passed to the ``Twig_Filter_Function`` constructor is the name
|
||||
of the PHP function to call, here ``str_rot13``, a native PHP function.
|
||||
|
||||
Let's say I now want to be able to add a prefix before the converted string:
|
||||
|
||||
.. code-block:: jinja
|
||||
|
||||
{{ "Twig"|rot13('prefix_') }}
|
||||
|
||||
{# should displays prefix_Gjvt #}
|
||||
|
||||
As the PHP ``str_rot13()`` function does not support this requirement, let's
|
||||
create a new PHP function::
|
||||
|
||||
function project_compute_rot13($string, $prefix = '')
|
||||
{
|
||||
return $prefix.str_rot13($string);
|
||||
}
|
||||
|
||||
As you can see, the ``prefix`` argument of the filter is passed as an extra
|
||||
argument to the ``project_compute_rot13()`` function.
|
||||
|
||||
Adding this filter is as easy as before::
|
||||
|
||||
$twig->addFilter('rot13', new Twig_Filter_Function('project_compute_rot13'));
|
||||
|
||||
For better encapsulation, a filter can also be defined as a static method of a
|
||||
class. The ``Twig_Filter_Function`` class can also be used to register such
|
||||
static methods as filters::
|
||||
|
||||
$twig->addFilter('rot13', new Twig_Filter_Function('SomeClass::rot13Filter'));
|
||||
|
||||
.. tip::
|
||||
|
||||
In an extension, you can also define a filter as a static method of the
|
||||
extension class.
|
||||
|
||||
Environment aware Filters
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
The ``Twig_Filter`` classes take options as their last argument. For instance,
|
||||
if you want access to the current environment instance in your filter, set the
|
||||
``needs_environment`` option to ``true``::
|
||||
|
||||
$filter = new Twig_Filter_Function('str_rot13', array('needs_environment' => true));
|
||||
|
||||
Twig will then pass the current environment as the first argument to the
|
||||
filter call::
|
||||
|
||||
function twig_compute_rot13(Twig_Environment $env, $string)
|
||||
{
|
||||
// get the current charset for instance
|
||||
$charset = $env->getCharset();
|
||||
|
||||
return str_rot13($string);
|
||||
}
|
||||
|
||||
Automatic Escaping
|
||||
~~~~~~~~~~~~~~~~~~
|
||||
|
||||
If automatic escaping is enabled, the output of the filter may be escaped
|
||||
before printing. If your filter acts as an escaper (or explicitly outputs HTML
|
||||
or JavaScript code), you will want the raw output to be printed. In such a
|
||||
case, set the ``is_safe`` option::
|
||||
|
||||
$filter = new Twig_Filter_Function('nl2br', array('is_safe' => array('html')));
|
||||
|
||||
Some filters may need to work on input that is already escaped or safe, for
|
||||
example when adding (safe) HTML tags to originally unsafe output. In such a
|
||||
case, set the ``pre_escape`` option to escape the input data before it is run
|
||||
through your filter::
|
||||
|
||||
$filter = new Twig_Filter_Function('somefilter', array('pre_escape' => 'html', 'is_safe' => array('html')));
|
||||
|
||||
Dynamic Filters
|
||||
~~~~~~~~~~~~~~~
|
||||
|
||||
.. versionadded:: 1.5
|
||||
Dynamic filters support was added in Twig 1.5.
|
||||
|
||||
A filter name containing the special ``*`` character is a dynamic filter as
|
||||
the ``*`` can be any string::
|
||||
|
||||
$twig->addFilter('*_path_*', new Twig_Filter_Function('twig_path'));
|
||||
|
||||
function twig_path($name, $arguments)
|
||||
{
|
||||
// ...
|
||||
}
|
||||
|
||||
The following filters will be matched by the above defined dynamic filter:
|
||||
|
||||
* ``product_path``
|
||||
* ``category_path``
|
||||
|
||||
A dynamic filter can define more than one dynamic parts::
|
||||
|
||||
$twig->addFilter('*_path_*', new Twig_Filter_Function('twig_path'));
|
||||
|
||||
function twig_path($name, $suffix, $arguments)
|
||||
{
|
||||
// ...
|
||||
}
|
||||
|
||||
The filter will receive all dynamic part values before the normal filters
|
||||
arguments. For instance, a call to ``'foo'|a_path_b()`` will result in the
|
||||
following PHP call: ``twig_path('a', 'b', 'foo')``.
|
||||
|
||||
Functions
|
||||
---------
|
||||
|
||||
A function is a regular PHP function or an object method that can be called from
|
||||
templates.
|
||||
|
||||
.. code-block:: jinja
|
||||
|
||||
{{ constant("DATE_W3C") }}
|
||||
|
||||
When compiling this template to PHP, Twig looks for the PHP callable
|
||||
associated with the ``constant`` function. The ``constant`` function is a built-in Twig
|
||||
function, and it is simply mapped to the PHP ``constant()`` function. After
|
||||
compilation, the generated PHP code is roughly equivalent to:
|
||||
|
||||
.. code-block:: html+php
|
||||
|
||||
<?php echo constant('DATE_W3C') ?>
|
||||
|
||||
Adding a function is similar to adding a filter. This can be done by calling the
|
||||
``addFunction()`` method on the ``Twig_Environment`` instance::
|
||||
|
||||
$twig = new Twig_Environment($loader);
|
||||
$twig->addFunction('functionName', new Twig_Function_Function('someFunction'));
|
||||
|
||||
You can also expose extension methods as functions in your templates::
|
||||
|
||||
// $this is an object that implements Twig_ExtensionInterface.
|
||||
$twig = new Twig_Environment($loader);
|
||||
$twig->addFunction('otherFunction', new Twig_Function_Method($this, 'someMethod'));
|
||||
|
||||
Functions also support ``needs_environment`` and ``is_safe`` parameters.
|
||||
|
||||
Dynamic Functions
|
||||
~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. versionadded:: 1.5
|
||||
Dynamic functions support was added in Twig 1.5.
|
||||
|
||||
A function name containing the special ``*`` character is a dynamic function
|
||||
as the ``*`` can be any string::
|
||||
|
||||
$twig->addFunction('*_path', new Twig_Function_Function('twig_path'));
|
||||
|
||||
function twig_path($name, $arguments)
|
||||
{
|
||||
// ...
|
||||
}
|
||||
|
||||
The following functions will be matched by the above defined dynamic function:
|
||||
|
||||
* ``product_path``
|
||||
* ``category_path``
|
||||
|
||||
A dynamic function can define more than one dynamic parts::
|
||||
|
||||
$twig->addFilter('*_path_*', new Twig_Filter_Function('twig_path'));
|
||||
|
||||
function twig_path($name, $suffix, $arguments)
|
||||
{
|
||||
// ...
|
||||
}
|
||||
|
||||
The function will receive all dynamic part values before the normal functions
|
||||
arguments. For instance, a call to ``a_path_b('foo')`` will result in the
|
||||
following PHP call: ``twig_path('a', 'b', 'foo')``.
|
||||
|
||||
Tags
|
||||
----
|
||||
|
||||
One of the most exciting feature of a template engine like Twig is the
|
||||
possibility to define new language constructs. This is also the most complex
|
||||
feature as you need to understand how Twig's internals work.
|
||||
|
||||
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:
|
||||
|
||||
.. code-block:: jinja
|
||||
|
||||
{% set name = "value" %}
|
||||
|
||||
{{ name }}
|
||||
|
||||
{# should output value #}
|
||||
|
||||
.. note::
|
||||
|
||||
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).
|
||||
|
||||
Three steps are needed to define a new tag:
|
||||
|
||||
* Defining a Token Parser class (responsible for parsing the template code);
|
||||
|
||||
* Defining a Node class (responsible for converting the parsed code to PHP);
|
||||
|
||||
* Registering the tag.
|
||||
|
||||
Registering a new tag
|
||||
~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Adding a tag is as simple as calling the ``addTokenParser`` method on the
|
||||
``Twig_Environment`` instance::
|
||||
|
||||
$twig = new Twig_Environment($loader);
|
||||
$twig->addTokenParser(new Project_Set_TokenParser());
|
||||
|
||||
Defining a Token Parser
|
||||
~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Now, let's see the actual code of this class::
|
||||
|
||||
class Project_Set_TokenParser extends Twig_TokenParser
|
||||
{
|
||||
public function parse(Twig_Token $token)
|
||||
{
|
||||
$lineno = $token->getLine();
|
||||
$name = $this->parser->getStream()->expect(Twig_Token::NAME_TYPE)->getValue();
|
||||
$this->parser->getStream()->expect(Twig_Token::OPERATOR_TYPE, '=');
|
||||
$value = $this->parser->getExpressionParser()->parseExpression();
|
||||
|
||||
$this->parser->getStream()->expect(Twig_Token::BLOCK_END_TYPE);
|
||||
|
||||
return new Project_Set_Node($name, $value, $lineno, $this->getTag());
|
||||
}
|
||||
|
||||
public function getTag()
|
||||
{
|
||||
return 'set';
|
||||
}
|
||||
}
|
||||
|
||||
The ``getTag()`` method must return the tag we want to parse, here ``set``.
|
||||
|
||||
The ``parse()`` method is invoked whenever the parser encounters a ``set``
|
||||
tag. It should return a ``Twig_Node`` instance that represents the node (the
|
||||
``Project_Set_Node`` calls creating is explained in the next section).
|
||||
|
||||
The parsing process is simplified thanks to a bunch of methods you can call
|
||||
from the token stream (``$this->parser->getStream()``):
|
||||
|
||||
* ``getCurrent()``: Gets the current token in the stream.
|
||||
|
||||
* ``next()``: Moves to the next token in the stream, *but returns the old one*.
|
||||
|
||||
* ``test($type)``, ``test($value)`` or ``test($type, $value)``: Determines whether
|
||||
the current token is of a particular type or value (or both). The value may be an
|
||||
array of several possible values.
|
||||
|
||||
* ``expect($type[, $value[, $message]])``: If the current token isn't of the given
|
||||
type/value a syntax error is thrown. Otherwise, if the type and value are correct,
|
||||
the token is returned and the stream moves to the next token.
|
||||
|
||||
* ``look()``: Looks a the next token without consuming it.
|
||||
|
||||
Parsing expressions is done by calling the ``parseExpression()`` like we did for
|
||||
the ``set`` tag.
|
||||
|
||||
.. tip::
|
||||
|
||||
Reading the existing ``TokenParser`` classes is the best way to learn all
|
||||
the nitty-gritty details of the parsing process.
|
||||
|
||||
Defining a Node
|
||||
~~~~~~~~~~~~~~~
|
||||
|
||||
The ``Project_Set_Node`` class itself is rather simple::
|
||||
|
||||
class Project_Set_Node extends Twig_Node
|
||||
{
|
||||
public function __construct($name, Twig_Node_Expression $value, $lineno, $tag = null)
|
||||
{
|
||||
parent::__construct(array('value' => $value), array('name' => $name), $lineno, $tag);
|
||||
}
|
||||
|
||||
public function compile(Twig_Compiler $compiler)
|
||||
{
|
||||
$compiler
|
||||
->addDebugInfo($this)
|
||||
->write('$context[\''.$this->getAttribute('name').'\'] = ')
|
||||
->subcompile($this->getNode('value'))
|
||||
->raw(";\n")
|
||||
;
|
||||
}
|
||||
}
|
||||
|
||||
The compiler implements a fluid interface and provides methods that helps the
|
||||
developer generate beautiful and readable PHP code:
|
||||
|
||||
* ``subcompile()``: Compiles a node.
|
||||
|
||||
* ``raw()``: Writes the given string as is.
|
||||
|
||||
* ``write()``: Writes the given string by adding indentation at the beginning
|
||||
of each line.
|
||||
|
||||
* ``string()``: Writes a quoted string.
|
||||
|
||||
* ``repr()``: Writes a PHP representation of a given value (see
|
||||
``Twig_Node_For`` for a usage example).
|
||||
|
||||
* ``addDebugInfo()``: Adds the line of the original template file related to
|
||||
the current node as a comment.
|
||||
|
||||
* ``indent()``: Indents the generated code (see ``Twig_Node_Block`` for a
|
||||
usage example).
|
||||
|
||||
* ``outdent()``: Outdents the generated code (see ``Twig_Node_Block`` for a
|
||||
usage example).
|
||||
|
||||
.. _creating_extensions:
|
||||
|
||||
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.
|
||||
|
||||
Creating an extension also makes for a better separation of code that is
|
||||
executed at compilation time and code needed at runtime. As such, it makes
|
||||
your code faster.
|
||||
|
||||
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.
|
||||
|
||||
.. tip::
|
||||
|
||||
When packaging your code into an extension, Twig is smart enough to
|
||||
recompile your templates whenever you make a change to it (when the
|
||||
``auto_reload`` is enabled).
|
||||
|
||||
.. note::
|
||||
|
||||
Before writing your own extensions, have a look at the Twig official
|
||||
extension repository: http://github.com/twigphp/Twig-extensions.
|
||||
|
||||
An extension is a class that implements the following interface::
|
||||
|
||||
interface Twig_ExtensionInterface
|
||||
{
|
||||
/**
|
||||
* Initializes the runtime environment.
|
||||
*
|
||||
* This is where you can load some file that contains filter functions for instance.
|
||||
*
|
||||
* @param Twig_Environment $environment The current Twig_Environment instance
|
||||
*/
|
||||
function initRuntime(Twig_Environment $environment);
|
||||
|
||||
/**
|
||||
* Returns the token parser instances to add to the existing list.
|
||||
*
|
||||
* @return array An array of Twig_TokenParserInterface or Twig_TokenParserBrokerInterface instances
|
||||
*/
|
||||
function getTokenParsers();
|
||||
|
||||
/**
|
||||
* Returns the node visitor instances to add to the existing list.
|
||||
*
|
||||
* @return array An array of Twig_NodeVisitorInterface instances
|
||||
*/
|
||||
function getNodeVisitors();
|
||||
|
||||
/**
|
||||
* Returns a list of filters to add to the existing list.
|
||||
*
|
||||
* @return array An array of filters
|
||||
*/
|
||||
function getFilters();
|
||||
|
||||
/**
|
||||
* Returns a list of tests to add to the existing list.
|
||||
*
|
||||
* @return array An array of tests
|
||||
*/
|
||||
function getTests();
|
||||
|
||||
/**
|
||||
* Returns a list of functions to add to the existing list.
|
||||
*
|
||||
* @return array An array of functions
|
||||
*/
|
||||
function getFunctions();
|
||||
|
||||
/**
|
||||
* Returns a list of operators to add to the existing list.
|
||||
*
|
||||
* @return array An array of operators
|
||||
*/
|
||||
function getOperators();
|
||||
|
||||
/**
|
||||
* Returns a list of global variables to add to the existing list.
|
||||
*
|
||||
* @return array An array of global variables
|
||||
*/
|
||||
function getGlobals();
|
||||
|
||||
/**
|
||||
* Returns the name of the extension.
|
||||
*
|
||||
* @return string The extension name
|
||||
*/
|
||||
function getName();
|
||||
}
|
||||
|
||||
To keep your extension class clean and lean, it can inherit from the built-in
|
||||
``Twig_Extension`` class instead of implementing the whole interface. That
|
||||
way, you just need to implement the ``getName()`` method as the
|
||||
``Twig_Extension`` provides empty implementations for all other methods.
|
||||
|
||||
The ``getName()`` method must return a unique identifier for your extension.
|
||||
|
||||
Now, with this information in mind, let's create the most basic extension
|
||||
possible::
|
||||
|
||||
class Project_Twig_Extension extends Twig_Extension
|
||||
{
|
||||
public function getName()
|
||||
{
|
||||
return 'project';
|
||||
}
|
||||
}
|
||||
|
||||
.. note::
|
||||
|
||||
Of course, 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 register an extension by using the ``addExtension()`` method on your
|
||||
main ``Environment`` object::
|
||||
|
||||
$twig = new Twig_Environment($loader);
|
||||
$twig->addExtension(new Project_Twig_Extension());
|
||||
|
||||
Of course, you need to first load the extension file by either using
|
||||
``require_once()`` or by using an autoloader (see `spl_autoload_register()`_).
|
||||
|
||||
.. tip::
|
||||
|
||||
The bundled extensions are great examples of how extensions work.
|
||||
|
||||
Globals
|
||||
~~~~~~~
|
||||
|
||||
Global variables can be registered in an extension via the ``getGlobals()``
|
||||
method::
|
||||
|
||||
class Project_Twig_Extension extends Twig_Extension
|
||||
{
|
||||
public function getGlobals()
|
||||
{
|
||||
return array(
|
||||
'text' => new Text(),
|
||||
);
|
||||
}
|
||||
|
||||
// ...
|
||||
}
|
||||
|
||||
Functions
|
||||
~~~~~~~~~
|
||||
|
||||
Functions can be registered in an extension via the ``getFunctions()``
|
||||
method::
|
||||
|
||||
class Project_Twig_Extension extends Twig_Extension
|
||||
{
|
||||
public function getFunctions()
|
||||
{
|
||||
return array(
|
||||
'lipsum' => new Twig_Function_Function('generate_lipsum'),
|
||||
);
|
||||
}
|
||||
|
||||
// ...
|
||||
}
|
||||
|
||||
Filters
|
||||
~~~~~~~
|
||||
|
||||
To add a filter to an extension, you need to override the ``getFilters()``
|
||||
method. This method must return an array of filters to add to the Twig
|
||||
environment::
|
||||
|
||||
class Project_Twig_Extension extends Twig_Extension
|
||||
{
|
||||
public function getFilters()
|
||||
{
|
||||
return array(
|
||||
'rot13' => new Twig_Filter_Function('str_rot13'),
|
||||
);
|
||||
}
|
||||
|
||||
// ...
|
||||
}
|
||||
|
||||
As you can see in the above code, the ``getFilters()`` method returns an array
|
||||
where keys are the name of the filters (``rot13``) and the values the
|
||||
definition of the filter (``new Twig_Filter_Function('str_rot13')``).
|
||||
|
||||
As seen in the previous chapter, you can also define filters as static methods
|
||||
on the extension class::
|
||||
|
||||
$twig->addFilter('rot13', new Twig_Filter_Function('Project_Twig_Extension::rot13Filter'));
|
||||
|
||||
You can also use ``Twig_Filter_Method`` instead of ``Twig_Filter_Function``
|
||||
when defining a filter to use a method::
|
||||
|
||||
class Project_Twig_Extension extends Twig_Extension
|
||||
{
|
||||
public function getFilters()
|
||||
{
|
||||
return array(
|
||||
'rot13' => new Twig_Filter_Method($this, 'rot13Filter'),
|
||||
);
|
||||
}
|
||||
|
||||
public function rot13Filter($string)
|
||||
{
|
||||
return str_rot13($string);
|
||||
}
|
||||
|
||||
// ...
|
||||
}
|
||||
|
||||
The first argument of the ``Twig_Filter_Method`` constructor is always
|
||||
``$this``, the current extension object. The second one is the name of the
|
||||
method to call.
|
||||
|
||||
Using methods for filters is a great way to package your filter without
|
||||
polluting the global namespace. This also gives the developer more flexibility
|
||||
at the cost of a small overhead.
|
||||
|
||||
Overriding default Filters
|
||||
..........................
|
||||
|
||||
If some default core filters do not suit your needs, you can easily override
|
||||
them by creating your own extension. Just use the same names as the one you
|
||||
want to override::
|
||||
|
||||
class MyCoreExtension extends Twig_Extension
|
||||
{
|
||||
public function getFilters()
|
||||
{
|
||||
return array(
|
||||
'date' => new Twig_Filter_Method($this, 'dateFilter'),
|
||||
// ...
|
||||
);
|
||||
}
|
||||
|
||||
public function dateFilter($timestamp, $format = 'F j, Y H:i')
|
||||
{
|
||||
return '...'.twig_date_format_filter($timestamp, $format);
|
||||
}
|
||||
|
||||
public function getName()
|
||||
{
|
||||
return 'project';
|
||||
}
|
||||
}
|
||||
|
||||
Here, we override the ``date`` filter with a custom one. Using this extension
|
||||
is as simple as registering the ``MyCoreExtension`` extension by calling the
|
||||
``addExtension()`` method on the environment instance::
|
||||
|
||||
$twig = new Twig_Environment($loader);
|
||||
$twig->addExtension(new MyCoreExtension());
|
||||
|
||||
Tags
|
||||
~~~~
|
||||
|
||||
Adding a tag in an extension can be done by overriding the
|
||||
``getTokenParsers()`` method. This method must return an array of tags to add
|
||||
to the Twig environment::
|
||||
|
||||
class Project_Twig_Extension extends Twig_Extension
|
||||
{
|
||||
public function getTokenParsers()
|
||||
{
|
||||
return array(new Project_Set_TokenParser());
|
||||
}
|
||||
|
||||
// ...
|
||||
}
|
||||
|
||||
In the above code, we have added a single new tag, defined by the
|
||||
``Project_Set_TokenParser`` class. The ``Project_Set_TokenParser`` class is
|
||||
responsible for parsing the tag and compiling it to PHP.
|
||||
|
||||
Operators
|
||||
~~~~~~~~~
|
||||
|
||||
The ``getOperators()`` methods allows to add new operators. Here is how to add
|
||||
``!``, ``||``, and ``&&`` operators::
|
||||
|
||||
class Project_Twig_Extension extends Twig_Extension
|
||||
{
|
||||
public function getOperators()
|
||||
{
|
||||
return array(
|
||||
array(
|
||||
'!' => array('precedence' => 50, 'class' => 'Twig_Node_Expression_Unary_Not'),
|
||||
),
|
||||
array(
|
||||
'||' => array('precedence' => 10, 'class' => 'Twig_Node_Expression_Binary_Or', 'associativity' => Twig_ExpressionParser::OPERATOR_LEFT),
|
||||
'&&' => array('precedence' => 15, 'class' => 'Twig_Node_Expression_Binary_And', 'associativity' => Twig_ExpressionParser::OPERATOR_LEFT),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// ...
|
||||
}
|
||||
|
||||
Tests
|
||||
~~~~~
|
||||
|
||||
The ``getTests()`` methods allows to add new test functions::
|
||||
|
||||
class Project_Twig_Extension extends Twig_Extension
|
||||
{
|
||||
public function getTests()
|
||||
{
|
||||
return array(
|
||||
'even' => new Twig_Test_Function('twig_test_even'),
|
||||
);
|
||||
}
|
||||
|
||||
// ...
|
||||
}
|
||||
|
||||
Testing an Extension
|
||||
--------------------
|
||||
|
||||
.. versionadded:: 1.10
|
||||
Support for functional tests was added in Twig 1.10.
|
||||
|
||||
Functional Tests
|
||||
~~~~~~~~~~~~~~~~
|
||||
|
||||
You can create functional tests for extensions simply by creating the
|
||||
following file structure in your test directory::
|
||||
|
||||
Fixtures/
|
||||
filters/
|
||||
foo.test
|
||||
bar.test
|
||||
functions/
|
||||
foo.test
|
||||
bar.test
|
||||
tags/
|
||||
foo.test
|
||||
bar.test
|
||||
IntegrationTest.php
|
||||
|
||||
The ``IntegrationTest.php`` file should look like this::
|
||||
|
||||
class Project_Tests_IntegrationTest extends Twig_Test_IntegrationTestCase
|
||||
{
|
||||
public function getExtensions()
|
||||
{
|
||||
return array(
|
||||
new Project_Twig_Extension1(),
|
||||
new Project_Twig_Extension2(),
|
||||
);
|
||||
}
|
||||
|
||||
public function getFixturesDir()
|
||||
{
|
||||
return dirname(__FILE__).'/Fixtures/';
|
||||
}
|
||||
}
|
||||
|
||||
Fixtures examples can be found within the Twig repository
|
||||
`tests/Twig/Fixtures`_ directory.
|
||||
|
||||
Node Tests
|
||||
~~~~~~~~~~
|
||||
|
||||
Testing the node visitors can be complex, so extend your test cases from
|
||||
``Twig_Test_NodeTestCase``. Examples can be found in the Twig repository
|
||||
`tests/Twig/Node`_ directory.
|
||||
|
||||
.. _`spl_autoload_register()`: http://www.php.net/spl_autoload_register
|
||||
.. _`rot13`: http://www.php.net/manual/en/function.str-rot13.php
|
||||
.. _`tests/Twig/Fixtures`: https://github.com/twigphp/Twig/tree/master/test/Twig/Tests/Fixtures
|
||||
.. _`tests/Twig/Node`: https://github.com/twigphp/Twig/tree/master/test/Twig/Tests/Node
|
||||
+2
-22
@@ -100,10 +100,6 @@ The following options are available:
|
||||
strategies); set it to ``false`` to disable auto-escaping. The ``filename``
|
||||
escaping strategy determines the escaping strategy to use for a template
|
||||
based on the template filename extension.
|
||||
|
||||
The ability to set the default escaping strategy was added in Twig 1.8 and
|
||||
the ``css``, ``url``, ``html_attr``, the callback strategies were added in
|
||||
Twig 1.9, and the ``filename`` escaping strategy was added in Twig 1.17.
|
||||
|
||||
* ``optimizations``: A flag that indicates which optimizations to apply
|
||||
(default to ``-1`` -- all optimizations are enabled; set it to ``0`` to
|
||||
@@ -132,9 +128,6 @@ Here is a list of the built-in loaders Twig provides:
|
||||
``Twig_Loader_Filesystem``
|
||||
..........................
|
||||
|
||||
.. versionadded:: 1.10
|
||||
The ``prependPath()`` and support for namespaces were added in Twig 1.10.
|
||||
|
||||
``Twig_Loader_Filesystem`` loads templates from the file system. This loader
|
||||
can find templates in folders on the file system and is the preferred way to
|
||||
load them::
|
||||
@@ -278,13 +271,6 @@ is still fresh, given the last modification time, or ``false`` otherwise.
|
||||
|
||||
The ``exists()`` method make your loader faster when used with the chain loader.
|
||||
|
||||
.. tip::
|
||||
|
||||
The ``exists()`` method is only part of ``Twig_LoaderInterface`` as of Twig
|
||||
2.0. In Twig 1.x, it is defined in ``Twig_ExistsLoaderInterface``, so you
|
||||
need to add it as an interface you implement when creating your own loader
|
||||
(only works as of Twig 1.11.0.)
|
||||
|
||||
Using Extensions
|
||||
----------------
|
||||
|
||||
@@ -303,8 +289,7 @@ Twig comes bundled with the following extensions:
|
||||
* *Twig_Extension_Sandbox*: 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_Profiler*: Enabled the built-in Twig profiler.
|
||||
|
||||
* *Twig_Extension_Optimizer*: Optimizes the node tree before compilation.
|
||||
|
||||
@@ -350,9 +335,7 @@ escaping strategy), except those using the ``raw`` filter:
|
||||
|
||||
{{ article.to_html|raw }}
|
||||
|
||||
You can also change the escaping mode locally by using the ``autoescape`` tag
|
||||
(see the :doc:`autoescape<tags/autoescape>` doc for the syntax used before
|
||||
Twig 1.8):
|
||||
You can also change the escaping mode locally by using the ``autoescape`` tag:
|
||||
|
||||
.. code-block:: jinja
|
||||
|
||||
@@ -477,9 +460,6 @@ the extension constructor::
|
||||
Profiler Extension
|
||||
~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. versionadded:: 1.18
|
||||
The Profile extension was added in Twig 1.18.
|
||||
|
||||
The ``profiler`` extension enables a profiler for Twig templates; it should
|
||||
only be used on your development machines as it adds some overhead::
|
||||
|
||||
|
||||
@@ -1,112 +0,0 @@
|
||||
Deprecated Features
|
||||
===================
|
||||
|
||||
This document lists all deprecated features in Twig. Deprecated features are
|
||||
kept for backward compatibility and removed in the next major release (a
|
||||
feature that was deprecated in Twig 1.x is removed in Twig 2.0).
|
||||
|
||||
Token Parsers
|
||||
-------------
|
||||
|
||||
* As of Twig 1.x, the token parser broker sub-system is deprecated. The
|
||||
following class and interface will be removed in 2.0:
|
||||
|
||||
* ``Twig_TokenParserBrokerInterface``
|
||||
* ``Twig_TokenParserBroker``
|
||||
|
||||
Extensions
|
||||
----------
|
||||
|
||||
* As of Twig 1.x, the ability to remove an extension is deprecated and the
|
||||
``Twig_Environment::removeExtension()`` method will be removed in 2.0.
|
||||
|
||||
PEAR
|
||||
----
|
||||
|
||||
PEAR support has been discontinued in Twig 1.15.1, and no PEAR packages are
|
||||
provided anymore. Use Composer instead.
|
||||
|
||||
Filters
|
||||
-------
|
||||
|
||||
* As of Twig 1.x, use ``Twig_SimpleFilter`` to add a filter. The following
|
||||
classes and interfaces will be removed in 2.0:
|
||||
|
||||
* ``Twig_FilterInterface``
|
||||
* ``Twig_FilterCallableInterface``
|
||||
* ``Twig_Filter``
|
||||
* ``Twig_Filter_Function``
|
||||
* ``Twig_Filter_Method``
|
||||
* ``Twig_Filter_Node``
|
||||
|
||||
* As of Twig 2.x, the ``Twig_SimpleFilter`` class is removed and replaced with
|
||||
the ``Twig_Filter`` class.
|
||||
|
||||
Functions
|
||||
---------
|
||||
|
||||
* As of Twig 1.x, use ``Twig_SimpleFunction`` to add a function. The following
|
||||
classes and interfaces will be removed in 2.0:
|
||||
|
||||
* ``Twig_FunctionInterface``
|
||||
* ``Twig_FunctionCallableInterface``
|
||||
* ``Twig_Function``
|
||||
* ``Twig_Function_Function``
|
||||
* ``Twig_Function_Method``
|
||||
* ``Twig_Function_Node``
|
||||
|
||||
* As of Twig 2.x, the ``Twig_SimpleFunction`` class is removed and replaced with
|
||||
the ``Twig_Function`` class.
|
||||
|
||||
Tests
|
||||
-----
|
||||
|
||||
* As of Twig 1.x, use ``Twig_SimpleTest`` to add a test. The following classes
|
||||
and interfaces will be removed in 2.0:
|
||||
|
||||
* ``Twig_TestInterface``
|
||||
* ``Twig_TestCallableInterface``
|
||||
* ``Twig_Test``
|
||||
* ``Twig_Test_Function``
|
||||
* ``Twig_Test_Method``
|
||||
* ``Twig_Test_Node``
|
||||
|
||||
* As of Twig 2.x, the ``Twig_SimpleTest`` class is removed and replaced with
|
||||
the ``Twig_Test`` class.
|
||||
|
||||
* The ``sameas`` and ``divisibleby`` tests are deprecated in favor of ``same
|
||||
as`` and ``divisible by`` respectively.
|
||||
|
||||
Nodes
|
||||
-----
|
||||
|
||||
* As of Twig 1.x, ``Node::toXml()`` is deprecated and will be removed in Twig
|
||||
2.0.
|
||||
|
||||
Interfaces
|
||||
----------
|
||||
|
||||
* As of Twig 1.x, the following interfaces are deprecated and empty (they will
|
||||
be removed in Twig 2.0):
|
||||
|
||||
* ``Twig_CompilerInterface`` (use ``Twig_Compiler`` instead)
|
||||
* ``Twig_LexerInterface`` (use ``Twig_Lexer`` instead)
|
||||
* ``Twig_NodeInterface`` (use ``Twig_Node`` instead)
|
||||
* ``Twig_ParserInterface`` (use ``Twig_Parser`` instead)
|
||||
* ``Twig_ExistsLoaderInterface`` (merged with ``Twig_LoaderInterface``)
|
||||
* ``Twig_TemplateInterface`` (use ``Twig_Template`` instead, and use
|
||||
those constants Twig_Template::ANY_CALL, Twig_Template::ARRAY_CALL,
|
||||
Twig_Template::METHOD_CALL)
|
||||
|
||||
Loaders
|
||||
-------
|
||||
|
||||
* As of Twig 1.x, ``Twig_Loader_String`` is deprecated and will be removed in
|
||||
2.0.
|
||||
|
||||
Globals
|
||||
-------
|
||||
|
||||
* As of Twig 2.x, the ability to register a global variable after the runtime
|
||||
or the extensions have been initialized is not possible anymore (but
|
||||
changing the value of an already registered global is possible).
|
||||
@@ -1,9 +1,6 @@
|
||||
``batch``
|
||||
=========
|
||||
|
||||
.. versionadded:: 1.12.3
|
||||
The ``batch`` filter was added in Twig 1.12.3.
|
||||
|
||||
The ``batch`` filter "batches" items by returning a list of lists with the
|
||||
given number of items. A second parameter can be provided and used to fill in
|
||||
missing items:
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
``convert_encoding``
|
||||
====================
|
||||
|
||||
.. versionadded:: 1.4
|
||||
The ``convert_encoding`` filter was added in Twig 1.4.
|
||||
|
||||
The ``convert_encoding`` filter converts a string from one encoding to
|
||||
another. The first argument is the expected output charset and the second one
|
||||
is the input charset:
|
||||
@@ -16,7 +13,7 @@ is the input charset:
|
||||
|
||||
This filter relies on the `iconv`_ or `mbstring`_ extension, so one of
|
||||
them must be installed. In case both are installed, `mbstring`_ is used by
|
||||
default (Twig before 1.8.1 uses `iconv`_ by default).
|
||||
default.
|
||||
|
||||
Arguments
|
||||
---------
|
||||
|
||||
@@ -1,18 +1,6 @@
|
||||
``date``
|
||||
========
|
||||
|
||||
.. versionadded:: 1.1
|
||||
The timezone support has been added in Twig 1.1.
|
||||
|
||||
.. versionadded:: 1.5
|
||||
The default date format support has been added in Twig 1.5.
|
||||
|
||||
.. versionadded:: 1.6.1
|
||||
The default timezone support has been added in Twig 1.6.1.
|
||||
|
||||
.. versionadded:: 1.11.0
|
||||
The introduction of the false value for the timezone was introduced in Twig 1.11.0
|
||||
|
||||
The ``date`` filter formats a date to a given format:
|
||||
|
||||
.. code-block:: jinja
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
``date_modify``
|
||||
===============
|
||||
|
||||
.. versionadded:: 1.9.0
|
||||
The date_modify filter has been added in Twig 1.9.0.
|
||||
|
||||
The ``date_modify`` filter modifies a date with a given modifier string:
|
||||
|
||||
.. code-block:: jinja
|
||||
|
||||
@@ -1,13 +1,6 @@
|
||||
``escape``
|
||||
==========
|
||||
|
||||
.. versionadded:: 1.9.0
|
||||
The ``css``, ``url``, and ``html_attr`` strategies were added in Twig
|
||||
1.9.0.
|
||||
|
||||
.. versionadded:: 1.14.0
|
||||
The ability to define custom escapers was added in Twig 1.14.0.
|
||||
|
||||
The ``escape`` filter escapes a string for safe insertion into the final
|
||||
output. It supports different escaping strategies depending on the template
|
||||
context.
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
``first``
|
||||
=========
|
||||
|
||||
.. versionadded:: 1.12.2
|
||||
The ``first`` filter was added in Twig 1.12.2.
|
||||
|
||||
The ``first`` filter returns the first "element" of a sequence, a mapping, or
|
||||
a string:
|
||||
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
``last``
|
||||
========
|
||||
|
||||
.. versionadded:: 1.12.2
|
||||
The ``last`` filter was added in Twig 1.12.2.
|
||||
|
||||
The ``last`` filter returns the last "element" of a sequence, a mapping, or
|
||||
a string:
|
||||
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
``nl2br``
|
||||
=========
|
||||
|
||||
.. versionadded:: 1.5
|
||||
The ``nl2br`` filter was added in Twig 1.5.
|
||||
|
||||
The ``nl2br`` filter inserts HTML line breaks before all newlines in a string:
|
||||
|
||||
.. code-block:: jinja
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
``number_format``
|
||||
=================
|
||||
|
||||
.. versionadded:: 1.5
|
||||
The ``number_format`` filter was added in Twig 1.5
|
||||
|
||||
The ``number_format`` filter formats numbers. It is a wrapper around PHP's
|
||||
`number_format`_ function:
|
||||
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
``reverse``
|
||||
===========
|
||||
|
||||
.. versionadded:: 1.6
|
||||
Support for strings has been added in Twig 1.6.
|
||||
|
||||
The ``reverse`` filter reverses a sequence, a mapping, or a string:
|
||||
|
||||
.. code-block:: jinja
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
``round``
|
||||
=========
|
||||
|
||||
.. versionadded:: 1.15.0
|
||||
The ``round`` filter was added in Twig 1.15.0.
|
||||
|
||||
The ``round`` filter rounds a number to a given precision:
|
||||
|
||||
.. code-block:: jinja
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
``slice``
|
||||
===========
|
||||
|
||||
.. versionadded:: 1.6
|
||||
The ``slice`` filter was added in Twig 1.6.
|
||||
|
||||
The ``slice`` filter extracts a slice of a sequence, a mapping, or a string:
|
||||
|
||||
.. code-block:: jinja
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
``split``
|
||||
=========
|
||||
|
||||
.. versionadded:: 1.10.3
|
||||
The ``split`` filter was added in Twig 1.10.3.
|
||||
|
||||
The ``split`` filter splits a string by the given delimiter and returns a list
|
||||
of strings:
|
||||
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
``trim``
|
||||
========
|
||||
|
||||
.. versionadded:: 1.6.2
|
||||
The ``trim`` filter was added in Twig 1.6.2.
|
||||
|
||||
The ``trim`` filter strips whitespace (or other characters) from the beginning
|
||||
and end of a string:
|
||||
|
||||
|
||||
@@ -1,13 +1,6 @@
|
||||
``url_encode``
|
||||
==============
|
||||
|
||||
.. versionadded:: 1.12.3
|
||||
Support for encoding an array as query string was added in Twig 1.12.3.
|
||||
|
||||
.. versionadded:: 1.16.0
|
||||
The ``raw`` argument was removed in Twig 1.16.0. Twig now always encodes
|
||||
according to RFC 3986.
|
||||
|
||||
The ``url_encode`` filter percent encodes a given string as URL segment
|
||||
or an array as query string:
|
||||
|
||||
@@ -24,11 +17,6 @@ or an array as query string:
|
||||
|
||||
.. note::
|
||||
|
||||
Internally, Twig uses the PHP `urlencode`_ (or `rawurlencode`_ if you pass
|
||||
``true`` as the first parameter) or the `http_build_query`_ function. Note
|
||||
that as of Twig 1.16.0, ``urlencode`` **always** uses ``rawurlencode`` (the
|
||||
``raw`` argument was removed.)
|
||||
Internally, Twig uses the PHP ``rawurlencode``.
|
||||
|
||||
.. _`urlencode`: http://php.net/urlencode
|
||||
.. _`rawurlencode`: http://php.net/rawurlencode
|
||||
.. _`http_build_query`: http://php.net/http_build_query
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
``attribute``
|
||||
=============
|
||||
|
||||
.. versionadded:: 1.2
|
||||
The ``attribute`` function was added in Twig 1.2.
|
||||
|
||||
The ``attribute`` function can be used to access a "dynamic" attribute of a
|
||||
variable:
|
||||
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
``constant``
|
||||
============
|
||||
|
||||
.. versionadded: 1.12.1
|
||||
constant now accepts object instances as the second argument.
|
||||
|
||||
``constant`` returns the constant value for a given string:
|
||||
|
||||
.. code-block:: jinja
|
||||
@@ -11,7 +8,7 @@
|
||||
{{ some_date|date(constant('DATE_W3C')) }}
|
||||
{{ constant('Namespace\\Classname::CONSTANT_NAME') }}
|
||||
|
||||
As of 1.12.1 you can read constants from object instances as well:
|
||||
You can read constants from object instances as well:
|
||||
|
||||
.. code-block:: jinja
|
||||
|
||||
|
||||
@@ -1,12 +1,6 @@
|
||||
``date``
|
||||
========
|
||||
|
||||
.. versionadded:: 1.6
|
||||
The date function has been added in Twig 1.6.
|
||||
|
||||
.. versionadded:: 1.6.1
|
||||
The default timezone support has been added in Twig 1.6.1.
|
||||
|
||||
Converts an argument to a date to allow date comparison:
|
||||
|
||||
.. code-block:: jinja
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
``dump``
|
||||
========
|
||||
|
||||
.. versionadded:: 1.5
|
||||
The ``dump`` function was added in Twig 1.5.
|
||||
|
||||
The ``dump`` function dumps information about a template variable. This is
|
||||
mostly useful to debug a template that does not behave as expected by
|
||||
introspecting its variables:
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
``include``
|
||||
===========
|
||||
|
||||
.. versionadded:: 1.12
|
||||
The ``include`` function was added in Twig 1.12.
|
||||
|
||||
The ``include`` function returns the rendered content of a template:
|
||||
|
||||
.. code-block:: jinja
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
``max``
|
||||
=======
|
||||
|
||||
.. versionadded:: 1.15
|
||||
The ``max`` function was added in Twig 1.15.
|
||||
|
||||
``max`` returns the biggest value of a sequence or a set of values:
|
||||
|
||||
.. code-block:: jinja
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
``min``
|
||||
=======
|
||||
|
||||
.. versionadded:: 1.15
|
||||
The ``min`` function was added in Twig 1.15.
|
||||
|
||||
``min`` returns the lowest value of a sequence or a set of values:
|
||||
|
||||
.. code-block:: jinja
|
||||
|
||||
@@ -1,12 +1,6 @@
|
||||
``random``
|
||||
==========
|
||||
|
||||
.. versionadded:: 1.5
|
||||
The ``random`` function was added in Twig 1.5.
|
||||
|
||||
.. versionadded:: 1.6
|
||||
String and integer handling was added in Twig 1.6.
|
||||
|
||||
The ``random`` function returns a random value depending on the supplied
|
||||
parameter type:
|
||||
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
``source``
|
||||
==========
|
||||
|
||||
.. versionadded:: 1.15
|
||||
The ``source`` function was added in Twig 1.15.
|
||||
|
||||
The ``source`` function returns the content of a template without rendering it:
|
||||
|
||||
.. code-block:: jinja
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
``template_from_string``
|
||||
========================
|
||||
|
||||
.. versionadded:: 1.11
|
||||
The ``template_from_string`` function was added in Twig 1.11.
|
||||
|
||||
The ``template_from_string`` function loads a template from a string:
|
||||
|
||||
.. code-block:: jinja
|
||||
|
||||
@@ -10,7 +10,6 @@ Twig
|
||||
api
|
||||
advanced
|
||||
internals
|
||||
deprecated
|
||||
recipes
|
||||
coding_standards
|
||||
tags/index
|
||||
|
||||
@@ -30,25 +30,9 @@ Installing the development version
|
||||
|
||||
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
|
||||
--------------------------
|
||||
|
||||
.. versionadded:: 1.4
|
||||
The C extension was added in Twig 1.4.
|
||||
|
||||
.. note::
|
||||
The C extension is **optional** but as it brings some nice performance
|
||||
improvements, you might want to install it in your production environment.
|
||||
@@ -64,17 +48,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`_
|
||||
|
||||
+1
-1
@@ -38,7 +38,7 @@ an instance of ``Twig_Token``, and the stream is an instance of
|
||||
* ``Twig_Token::STRING_TYPE``: A string in an expression;
|
||||
* ``Twig_Token::OPERATOR_TYPE``: An operator;
|
||||
* ``Twig_Token::PUNCTUATION_TYPE``: A punctuation sign;
|
||||
* ``Twig_Token::INTERPOLATION_START_TYPE``, ``Twig_Token::INTERPOLATION_END_TYPE`` (as of Twig 1.5): Delimiters for string interpolation;
|
||||
* ``Twig_Token::INTERPOLATION_START_TYPE``, ``Twig_Token::INTERPOLATION_END_TYPE``: Delimiters for string interpolation;
|
||||
* ``Twig_Token::EOF_TYPE``: Ends of template.
|
||||
|
||||
You can manually convert a source code into a token stream by calling the
|
||||
|
||||
+1
-6
@@ -319,9 +319,6 @@ This can be easily achieved with the following code::
|
||||
Using the Template name to set the default Escaping Strategy
|
||||
------------------------------------------------------------
|
||||
|
||||
.. versionadded:: 1.8
|
||||
This recipe requires Twig 1.8 or later.
|
||||
|
||||
The ``autoescape`` option determines the default escaping strategy to use when
|
||||
no escaping is applied on a variable. When Twig is used to mostly generate
|
||||
HTML files, you can set it to ``html`` and explicitly change it to ``js`` when
|
||||
@@ -391,7 +388,7 @@ We have created a simple ``templates`` table that hosts two templates:
|
||||
|
||||
Now, let's define a loader able to use this database::
|
||||
|
||||
class DatabaseTwigLoader implements Twig_LoaderInterface, Twig_ExistsLoaderInterface
|
||||
class DatabaseTwigLoader implements Twig_LoaderInterface
|
||||
{
|
||||
protected $dbh;
|
||||
|
||||
@@ -409,8 +406,6 @@ Now, let's define a loader able to use this database::
|
||||
return $source;
|
||||
}
|
||||
|
||||
// Twig_ExistsLoaderInterface as of Twig 1.11
|
||||
// part of Twig_LoaderInterface as of Twig 2.0
|
||||
public function exists($name)
|
||||
{
|
||||
return $name === $this->getValue('name', $name);
|
||||
|
||||
@@ -6,8 +6,6 @@ template to be escaped or not by using the ``autoescape`` tag:
|
||||
|
||||
.. code-block:: jinja
|
||||
|
||||
{# The following syntax works as of Twig 1.8 -- see the note below for previous versions #}
|
||||
|
||||
{% autoescape %}
|
||||
Everything will be automatically escaped in this block
|
||||
using the HTML strategy
|
||||
@@ -27,26 +25,6 @@ template to be escaped or not by using the ``autoescape`` tag:
|
||||
Everything will be outputted as is in this block
|
||||
{% endautoescape %}
|
||||
|
||||
.. note::
|
||||
|
||||
Before Twig 1.8, the syntax was different:
|
||||
|
||||
.. code-block:: jinja
|
||||
|
||||
{% autoescape true %}
|
||||
Everything will be automatically escaped in this block
|
||||
using the HTML strategy
|
||||
{% endautoescape %}
|
||||
|
||||
{% autoescape false %}
|
||||
Everything will be outputted as is in this block
|
||||
{% endautoescape %}
|
||||
|
||||
{% autoescape true js %}
|
||||
Everything will be automatically escaped in this block
|
||||
using the js escaping strategy
|
||||
{% endautoescape %}
|
||||
|
||||
When automatic escaping is enabled everything is escaped by default except for
|
||||
values explicitly marked as safe. Those can be marked in the template by using
|
||||
the :doc:`raw<../filters/raw>` filter:
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
``do``
|
||||
======
|
||||
|
||||
.. versionadded:: 1.5
|
||||
The ``do`` tag was added in Twig 1.5.
|
||||
|
||||
The ``do`` tag works exactly like the regular variable expression (``{{ ...
|
||||
}}``) just that it doesn't print anything:
|
||||
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
``embed``
|
||||
=========
|
||||
|
||||
.. versionadded:: 1.8
|
||||
The ``embed`` tag was added in Twig 1.8.
|
||||
|
||||
The ``embed`` tag combines the behaviour of :doc:`include<include>` and
|
||||
:doc:`extends<extends>`.
|
||||
It allows you to include another template's contents, just like ``include``
|
||||
|
||||
@@ -162,9 +162,6 @@ the parent template::
|
||||
|
||||
$twig->display('template.twig', array('layout' => $layout));
|
||||
|
||||
.. versionadded:: 1.2
|
||||
The possibility to pass an array of templates has been added in Twig 1.2.
|
||||
|
||||
You can also provide a list of templates that are checked for existence. The
|
||||
first template that exists will be used as a parent:
|
||||
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
``flush``
|
||||
=========
|
||||
|
||||
.. versionadded:: 1.5
|
||||
The flush tag was added in Twig 1.5.
|
||||
|
||||
The ``flush`` tag tells Twig to flush the output buffer:
|
||||
|
||||
.. code-block:: jinja
|
||||
|
||||
@@ -81,9 +81,6 @@ Variable Description
|
||||
implement the ``Countable`` interface. They are also not available when
|
||||
looping with a condition.
|
||||
|
||||
.. versionadded:: 1.2
|
||||
The ``if`` modifier support has been added in Twig 1.2.
|
||||
|
||||
Adding a condition
|
||||
------------------
|
||||
|
||||
|
||||
@@ -59,9 +59,6 @@ directly::
|
||||
|
||||
$twig->loadTemplate('template.twig')->display(array('template' => $template));
|
||||
|
||||
.. versionadded:: 1.2
|
||||
The ``ignore missing`` feature has been added in Twig 1.2.
|
||||
|
||||
You can mark an include with ``ignore missing`` in which case Twig will ignore
|
||||
the statement if the template to be included does not exist. It has to be
|
||||
placed just after the template name. Here some valid examples:
|
||||
@@ -72,9 +69,6 @@ placed just after the template name. Here some valid examples:
|
||||
{% include 'sidebar.html' ignore missing with {'foo': 'bar'} %}
|
||||
{% include 'sidebar.html' ignore missing only %}
|
||||
|
||||
.. versionadded:: 1.2
|
||||
The possibility to pass an array of templates has been added in Twig 1.2.
|
||||
|
||||
You can also provide a list of templates that are checked for existence before
|
||||
inclusion. The first template that exists will be included:
|
||||
|
||||
|
||||
+1
-8
@@ -1,9 +1,6 @@
|
||||
``use``
|
||||
=======
|
||||
|
||||
.. versionadded:: 1.1
|
||||
Horizontal reuse was added in Twig 1.1.
|
||||
|
||||
.. note::
|
||||
|
||||
Horizontal reuse is an advanced Twig feature that is hardly ever needed in
|
||||
@@ -80,9 +77,6 @@ is ignored. To avoid name conflicts, you can rename imported blocks:
|
||||
{% block title %}{% endblock %}
|
||||
{% block content %}{% endblock %}
|
||||
|
||||
.. versionadded:: 1.3
|
||||
The ``parent()`` support was added in Twig 1.3.
|
||||
|
||||
The ``parent()`` function automatically determines the correct inheritance
|
||||
tree, so it can be used when overriding a block defined in an imported
|
||||
template:
|
||||
@@ -105,8 +99,7 @@ the ``blocks.html`` template.
|
||||
|
||||
.. tip::
|
||||
|
||||
In Twig 1.2, renaming allows you to simulate inheritance by calling the
|
||||
"parent" block:
|
||||
Renaming allows you to simulate inheritance by calling the "parent" block:
|
||||
|
||||
.. code-block:: jinja
|
||||
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
``verbatim``
|
||||
============
|
||||
|
||||
.. versionadded:: 1.12
|
||||
The ``verbatim`` tag was added in Twig 1.12 (it was named ``raw`` before).
|
||||
|
||||
The ``verbatim`` tag marks sections as being raw text that should not be
|
||||
parsed. For example to put Twig syntax as example into a template you can use
|
||||
this snippet:
|
||||
@@ -17,8 +14,3 @@ this snippet:
|
||||
{% endfor %}
|
||||
</ul>
|
||||
{% endverbatim %}
|
||||
|
||||
.. note::
|
||||
|
||||
The ``verbatim`` tag works in the exact same way as the old ``raw`` tag,
|
||||
but was renamed to avoid confusion with the ``raw`` filter.
|
||||
+2
-22
@@ -195,9 +195,6 @@ built-in functions.
|
||||
Named Arguments
|
||||
---------------
|
||||
|
||||
.. versionadded:: 1.12
|
||||
Support for named arguments was added in Twig 1.12.
|
||||
|
||||
.. code-block:: jinja
|
||||
|
||||
{% for i in range(low=1, high=10, step=2) %}
|
||||
@@ -494,9 +491,6 @@ For bigger sections it makes sense to mark a block
|
||||
Macros
|
||||
------
|
||||
|
||||
.. versionadded:: 1.12
|
||||
Support for default argument values was added in Twig 1.12.
|
||||
|
||||
Macros are comparable with functions in regular programming languages. They
|
||||
are useful to reuse often used HTML fragments to not repeat yourself.
|
||||
|
||||
@@ -570,9 +564,6 @@ even if you're not working with PHP you should feel comfortable with it.
|
||||
Literals
|
||||
~~~~~~~~
|
||||
|
||||
.. versionadded:: 1.5
|
||||
Support for hash keys as names and expressions was added in Twig 1.5.
|
||||
|
||||
The simplest form of expressions are literals. Literals are representations
|
||||
for PHP types such as strings, numbers, and arrays. The following literals
|
||||
exist:
|
||||
@@ -598,13 +589,13 @@ exist:
|
||||
{# keys as string #}
|
||||
{ 'foo': 'foo', 'bar': 'bar' }
|
||||
|
||||
{# keys as names (equivalent to the previous hash) -- as of Twig 1.5 #}
|
||||
{# keys as names (equivalent to the previous hash) #}
|
||||
{ foo: 'foo', bar: 'bar' }
|
||||
|
||||
{# keys as integer #}
|
||||
{ 2: 'foo', 4: 'bar' }
|
||||
|
||||
{# keys as expressions (the expression must be enclosed into parentheses) -- as of Twig 1.5 #}
|
||||
{# keys as expressions (the expression must be enclosed into parentheses) #}
|
||||
{ (1 + 1): 'foo', (a ~ 'b'): 'bar' }
|
||||
|
||||
* ``true`` / ``false``: ``true`` represents the true value, ``false``
|
||||
@@ -758,9 +749,6 @@ tests.
|
||||
Other Operators
|
||||
~~~~~~~~~~~~~~~
|
||||
|
||||
.. versionadded:: 1.12.0
|
||||
Support for the extended ternary operator was added in Twig 1.12.0.
|
||||
|
||||
The following operators are very useful but don't fit into any of the other
|
||||
categories:
|
||||
|
||||
@@ -781,17 +769,12 @@ categories:
|
||||
.. code-block:: jinja
|
||||
|
||||
{{ foo ? 'yes' : 'no' }}
|
||||
|
||||
{# as of Twig 1.12.0 #}
|
||||
{{ foo ?: 'no' }} is the same as {{ foo ? foo : 'no' }}
|
||||
{{ foo ? 'yes' }} is the same as {{ foo ? 'yes' : '' }}
|
||||
|
||||
String Interpolation
|
||||
~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. versionadded:: 1.5
|
||||
String interpolation was added in Twig 1.5.
|
||||
|
||||
String interpolation (`#{expression}`) allows any valid expression to appear
|
||||
within a *double-quoted string*. The result of evaluating that expression is
|
||||
inserted into the string:
|
||||
@@ -804,9 +787,6 @@ inserted into the string:
|
||||
Whitespace Control
|
||||
------------------
|
||||
|
||||
.. versionadded:: 1.1
|
||||
Tag level whitespace control was added in Twig 1.1.
|
||||
|
||||
The first newline after a template tag is removed automatically (like in PHP.)
|
||||
Whitespace is not further modified by the template engine, so each whitespace
|
||||
(spaces, tabs, newlines etc.) is returned unchanged.
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
``constant``
|
||||
============
|
||||
|
||||
.. versionadded: 1.13.1
|
||||
constant now accepts object instances as the second argument.
|
||||
|
||||
``constant`` checks if a variable has the exact same value as a constant. You
|
||||
can use either global constants or class constants:
|
||||
|
||||
|
||||
@@ -1,13 +1,6 @@
|
||||
``divisible by``
|
||||
================
|
||||
|
||||
.. versionadded:: 1.14.2
|
||||
The ``divisible by`` test was added in Twig 1.14.2 as an alias for
|
||||
``divisibleby``.
|
||||
|
||||
.. versionadded:: 2.0
|
||||
The ``divisibleby`` test was removed. Use ``divisible by`` instead.
|
||||
|
||||
``divisible by`` checks if a variable is divisible by a number:
|
||||
|
||||
.. code-block:: jinja
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
``iterable``
|
||||
============
|
||||
|
||||
.. versionadded:: 1.7
|
||||
The iterable test was added in Twig 1.7.
|
||||
|
||||
``iterable`` checks if a variable is an array or a traversable object:
|
||||
|
||||
.. code-block:: jinja
|
||||
|
||||
@@ -1,12 +1,6 @@
|
||||
``same as``
|
||||
===========
|
||||
|
||||
.. versionadded:: 1.14.2
|
||||
The ``same as`` test was added in Twig 1.14.2 as an alias for ``sameas``.
|
||||
|
||||
.. versionadded:: 2.0
|
||||
The ``sameas`` test was removed. Use ``same as`` instead.
|
||||
|
||||
``same as`` checks if a variable is the same as another variable.
|
||||
This is the equivalent to ``===`` in PHP:
|
||||
|
||||
|
||||
Reference in New Issue
Block a user