This section describes how to extend Twig as of Twig 1.12. If you are using an older version, read the 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.
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.
When extending Twig without creating an extension, 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.
{% %}: 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).
In fact, you rarely need to create tags; and that's good news because tags are the most complex extension point of Twig.
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).
As a rule of thumb, use functions for frequently used features and global objects for everything else.
What?
Implementation difficulty?
How often?
When?
The first argument passed to the Twig_SimpleFilter constructor is the name of the filter you will use in templates and the second one is the PHP callable to associate with it.
When called by Twig, the PHP callable receives the left side of the filter (before the pipe |) as the first argument and the extra arguments passed to the filter (within parentheses ()) as extra arguments.
// ...
// ...
New in version 1.19: Support for variadic filters was added in Twig 1.19.
// ...
Be warned that named arguments passed to a variadic filter cannot be checked for validity as they will automatically end up in the option array.
// ...
// ...
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').
New in version 1.21: Support for deprecated filters was added in Twig 1.21.
// ...
When a filter is deprecated, Twig emits a deprecation notice when compiling a template using it. See Displaying Deprecation Notices for more information.
// ...
Functions support the same features as filters, except for the pre_escape and preserves_safety options.
// ...
Test functions should always return true/false.
The node sub-node will contain an expression of my_value. Node-based tests also have access to the arguments node. This node will contain the 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 also support dynamic name feature as filters and functions.
One of the most exciting features 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.
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).
Registering the tag.
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).
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 at the next token without consuming it.
Parsing expressions is done by calling the parseExpression() like we did for the set tag.
Reading the existing TokenParser classes is the best way to learn all the nitty-gritty details of the parsing process.
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).
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.
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.
When packaging your code into an extension, Twig is smart enough to recompile your templates whenever you make a change to it (when auto_reload is enabled).
Before writing your own extensions, have a look at the Twig official extension repository: http://github.com/twigphp/Twig-extensions.
* Initializes the runtime environment.
* This is where you can load some file that contains filter functions for instance.
* Returns the token parser instances to add to the existing list.
* Returns the node visitor instances to add to the existing list.
* Returns a list of filters to add to the existing list.
* Returns a list of tests to add to the existing list.
* Returns a list of functions to add to the existing list.
* Returns a list of operators to add to the existing list.
* Returns a list of global variables to add to the existing list.
* Returns the name of the extension.
Of course, this extension does nothing for now. We will customize it in the next sections.
Prior to Twig 1.26, you must implement the getName() method which must return a unique identifier for the extension.
Twig does not care where you save your extension on the filesystem, as all extensions must be registered explicitly to be available in your templates.
The Twig core extensions are great examples of how extensions work.
// ...
// ...
// ...
// ...
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.
// ...
// ...
object methods: More flexible and required if your runtime code depends on external objects.
This is very convenient but not recommended as it makes template compilation depend on runtime dependencies even if they are not needed (think for instance as a dependency that connects to a database engine).
// ...
As of Twig 1.32, Twig comes with a PSR-11 compatible runtime loader (Twig_ContainerRuntimeLoader) that works on PHP 5.3+.
Here, we have overloaded the built-in date filter with a custom one.
Note that overloading the built-in Twig elements is not recommended as it might be confusing.
Fixtures examples can be found within the Twig repository tests/Twig/Fixtures directory.
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.
Licensed under the three clause BSD license.
