💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
# Extending Twig Caution This section describes how to extend Twig as of **Twig 1.12**. If you areusing an older version, read the [*legacy*](#) chapterinstead. Twig can be extended in many ways; you can add extra tags, filters, tests,operators, global variables, and functions. You can even extend the parseritself with node visitors. Note The first section of this chapter describes how to extend Twig easily. Ifyou want to reuse your changes in different projects or if you want toshare them with others, you should then create an extension as describedin the following section. Caution When extending Twig without creating an extension, Twig won't be able torecompile your templates when the PHP code is updated. To see your changesin real-time, either disable template caching or package your code into anextension (see the next section of this chapter). Before extending Twig, you must understand the differences between all thedifferent 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 toimplement a *Lorem ipsum* generator (it needs to know the number of words togenerate). You can use a `lipsum`*tag*: <table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1</pre></div></td><td class="code"><div class="highlight"><pre>{% lipsum 40 %} </pre></div></td></tr></table> That works, but using a tag for `lipsum` is not a good idea for at leastthree 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: ~~~ {{ 'some text' ~ {% lipsum 40 %} ~ 'some more text' }} ~~~ In fact, you rarely need to create tags; and that's good news because tags arethe most complex extension point of Twig. Now, let's use a `lipsum`*filter*: <table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1</pre></div></td><td class="code"><div class="highlight"><pre>{{ 40|lipsum }} </pre></div></td></tr></table> Again, it works, but it looks weird. A filter transforms the passed value tosomething else but here we use the value to indicate the number of words togenerate (so, `40` is an argument of the filter, not the value we want totransform). Next, let's use a `lipsum`*function*: <table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1</pre></div></td><td class="code"><div class="highlight"><pre>{{ lipsum(40) }} </pre></div></td></tr></table> Here we go. For this specific example, the creation of a function is theextension point to use. And you can use it anywhere an expression is accepted: <table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1 2 3</pre></div></td><td class="code"><div class="highlight"><pre>{{ 'some text' ~ lipsum(40) ~ 'some more text' }} {% set lipsum = lipsum(40) %} </pre></div></td></tr></table> Last but not the least, you can also use a *global* object with a method ableto generate lorem ipsum text: <table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1</pre></div></td><td class="code"><div class="highlight"><pre>{{ text.lipsum(40) }} </pre></div></td></tr></table> As a rule of thumb, use functions for frequently used features and globalobjects 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'savailable in all templates and macros: <table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1 2</pre></div></td><td class="code"><div class="highlight"><pre>$twig = new Twig_Environment($loader); $twig-&gt;addGlobal('text', new Text()); </pre></div></td></tr></table> You can then use the `text` variable anywhere in a template: <table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1</pre></div></td><td class="code"><div class="highlight"><pre>{{ text.lipsum(40) }} </pre></div></td></tr></table> ### Filters Creating a filter is as simple as associating a name with a PHP callable: <table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre> 1 2 3 4 5 6 7 8 9 10</pre></div></td><td class="code"><div class="highlight"><pre>// an anonymous function $filter = new Twig_SimpleFilter('rot13', function ($string) { return str_rot13($string); }); // or a simple PHP function $filter = new Twig_SimpleFilter('rot13', 'str_rot13'); // or a class method $filter = new Twig_SimpleFilter('rot13', array('SomeClass', 'rot13Filter')); </pre></div></td></tr></table> The first argument passed to the `Twig_SimpleFilter` constructor is the nameof the filter you will use in templates and the second one is the PHP callableto associate with it. Then, add the filter to your Twig environment: <table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1 2</pre></div></td><td class="code"><div class="highlight"><pre>$twig = new Twig_Environment($loader); $twig-&gt;addFilter($filter); </pre></div></td></tr></table> And here is how to use it in a template: <table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1 2 3</pre></div></td><td class="code"><div class="highlight"><pre>{{ 'Twig'|rot13 }} {# will output Gjvt #} </pre></div></td></tr></table> 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 passedto the filter (within parentheses `()`) as extra arguments. For instance, the following code: <table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1 2</pre></div></td><td class="code"><div class="highlight"><pre>{{ 'TWIG'|lower }} {{ now|date('d/m/Y') }} </pre></div></td></tr></table> is compiled to something like the following: <table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1 2</pre></div></td><td class="code"><div class="highlight"><pre>&lt;?php echo strtolower('TWIG') ?&gt; &lt;?php echo twig_date_format_filter($now, 'd/m/Y') ?&gt; </pre></div></td></tr></table> The `Twig_SimpleFilter` class takes an array of options as its lastargument: <table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1</pre></div></td><td class="code"><div class="highlight"><pre>$filter = new Twig_SimpleFilter('rot13', 'str_rot13', $options); </pre></div></td></tr></table> ### Environment-aware Filters If you want to access the current environment instance in your filter, set the`needs_environment` option to `true`; Twig will pass the currentenvironment as the first argument to the filter call: <table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1 2 3 4 5 6</pre></div></td><td class="code"><div class="highlight"><pre>$filter = new Twig_SimpleFilter('rot13', function (Twig_Environment $env, $string) { // get the current charset for instance $charset = $env-&gt;getCharset(); return str_rot13($string); }, array('needs_environment' =&gt; true)); </pre></div></td></tr></table> ### Context-aware Filters If you want to access the current context in your filter, set the`needs_context` option to `true`; Twig will pass the current context asthe first argument to the filter call (or the second one if`needs_environment` is also set to `true`): <table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1 2 3 4 5 6 7</pre></div></td><td class="code"><div class="highlight"><pre>$filter = new Twig_SimpleFilter('rot13', function ($context, $string) { // ... }, array('needs_context' =&gt; true)); $filter = new Twig_SimpleFilter('rot13', function (Twig_Environment $env, $context, $string) { // ... }, array('needs_context' =&gt; true, 'needs_environment' =&gt; true)); </pre></div></td></tr></table> ### Automatic Escaping If automatic escaping is enabled, the output of the filter may be escapedbefore printing. If your filter acts as an escaper (or explicitly outputs HTMLor JavaScript code), you will want the raw output to be printed. In such acase, set the `is_safe` option: <table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1</pre></div></td><td class="code"><div class="highlight"><pre>$filter = new Twig_SimpleFilter('nl2br', 'nl2br', array('is_safe' =&gt; array('html'))); </pre></div></td></tr></table> Some filters may need to work on input that is already escaped or safe, forexample when adding (safe) HTML tags to originally unsafe output. In such acase, set the `pre_escape` option to escape the input data before it is runthrough your filter: <table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1</pre></div></td><td class="code"><div class="highlight"><pre>$filter = new Twig_SimpleFilter('somefilter', 'somefilter', array('pre_escape' =&gt; 'html', 'is_safe' =&gt; array('html'))); </pre></div></td></tr></table> ### Variadic Filters New in version 1.19: Support for variadic filters was added in Twig 1.19. When a filter should accept an arbitrary number of arguments, set the`is_variadic` option to `true`; Twig will pass the extra arguments as thelast argument to the filter call as an array: <table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1 2 3</pre></div></td><td class="code"><div class="highlight"><pre>$filter = new Twig_SimpleFilter('thumbnail', function ($file, array $options = array()) { // ... }, array('is_variadic' =&gt; true)); </pre></div></td></tr></table> Be warned that named arguments passed to a variadic filter cannot be checkedfor validity as they will automatically end up in the option array. ### Dynamic Filters A filter name containing the special `*` character is a dynamic filter asthe `*` can be any string: <table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1 2 3</pre></div></td><td class="code"><div class="highlight"><pre>$filter = new Twig_SimpleFilter('*_path', function ($name, $arguments) { // ... }); </pre></div></td></tr></table> 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: <table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1 2 3</pre></div></td><td class="code"><div class="highlight"><pre>$filter = new Twig_SimpleFilter('*_path_*', function ($name, $suffix, $arguments) { // ... }); </pre></div></td></tr></table> The filter will receive all dynamic part values before the normal filterarguments, 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 tothe filter: `('a', 'b', 'foo')`. ### Deprecated Filters New in version 1.21: Support for deprecated filters was added in Twig 1.21. You can mark a filter as being deprecated by setting the `deprecated` optionto `true`. You can also give an alternative filter that replaces thedeprecated one when that makes sense: <table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1 2 3</pre></div></td><td class="code"><div class="highlight"><pre>$filter = new Twig_SimpleFilter('obsolete', function () { // ... }, array('deprecated' =&gt; true, 'alternative' =&gt; 'new_one')); </pre></div></td></tr></table> When a filter is deprecated, Twig emits a deprecation notice when compiling atemplate using it. See [*Displaying Deprecation Notices*](#) for more information. ### Functions Functions are defined in the exact same way as filters, but you need to createan instance of `Twig_SimpleFunction`: <table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1 2 3 4 5</pre></div></td><td class="code"><div class="highlight"><pre>$twig = new Twig_Environment($loader); $function = new Twig_SimpleFunction('function_name', function () { // ... }); $twig-&gt;addFunction($function); </pre></div></td></tr></table> Functions support the same features as filters, except for the `pre_escape`and `preserves_safety` options. ### Tests Tests are defined in the exact same way as filters and functions, but you needto create an instance of `Twig_SimpleTest`: <table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1 2 3 4 5</pre></div></td><td class="code"><div class="highlight"><pre>$twig = new Twig_Environment($loader); $test = new Twig_SimpleTest('test_name', function () { // ... }); $twig-&gt;addTest($test); </pre></div></td></tr></table> Tests allow you to create custom application specific logic for evaluatingboolean conditions. As a simple example, let's create a Twig test that checks ifobjects are 'red': <table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre> 1 2 3 4 5 6 7 8 9 10 11</pre></div></td><td class="code"><div class="highlight"><pre>$twig = new Twig_Environment($loader); $test = new Twig_SimpleTest('red', function ($value) { if (isset($value-&gt;color) &amp;&amp; $value-&gt;color == 'red') { return true; } if (isset($value-&gt;paint) &amp;&amp; $value-&gt;paint == 'red') { return true; } return false; }); $twig-&gt;addTest($test); </pre></div></td></tr></table> Test functions should always return true/false. When creating tests you can use the `node_class` option to provide custom testcompilation. This is useful if your test can be compiled into PHP primitives.This is used by many of the tests built into Twig: <table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre> 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19</pre></div></td><td class="code"><div class="highlight"><pre>$twig = new Twig_Environment($loader); $test = new Twig_SimpleTest( 'odd', null, array('node_class' =&gt; 'Twig_Node_Expression_Test_Odd')); $twig-&gt;addTest($test); class Twig_Node_Expression_Test_Odd extends Twig_Node_Expression_Test { public function compile(Twig_Compiler $compiler) { $compiler -&gt;raw('(') -&gt;subcompile($this-&gt;getNode('node')) -&gt;raw(' % 2 == 1') -&gt;raw(')') ; } } </pre></div></td></tr></table> The above example shows how you can create tests that use a node class. Thenode class has access to one sub-node called 'node'. This sub-node contains thevalue that is being tested. When the `odd` filter is used in code such as: <table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1</pre></div></td><td class="code"><div class="highlight"><pre>{% if my_value is odd %} </pre></div></td></tr></table> The `node` sub-node will contain an expression of `my_value`. Node-basedtests also have access to the `arguments` node. This node will contain thevarious other arguments that have been provided to your test. If you want to pass a variable number of positional or named arguments to thetest, set the `is_variadic` option to `true`. Tests also support dynamicname feature as filters and functions. ### Tags One of the most exciting features of a template engine like Twig is thepossibility to define new language constructs. This is also the most complexfeature as you need to understand how Twig's internals work. Let's create a simple `set` tag that allows the definition of simplevariables from within a template. The tag can be used like follows: <table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1 2 3 4 5</pre></div></td><td class="code"><div class="highlight"><pre>{% set name = "value" %} {{ name }} {# should output value #} </pre></div></td></tr></table> Note The `set` tag is part of the Core extension and as such is alwaysavailable. The built-in version is slightly more powerful and supportsmultiple assignments by default (cf. the template designers chapter formore 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: <table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1 2</pre></div></td><td class="code"><div class="highlight"><pre>$twig = new Twig_Environment($loader); $twig-&gt;addTokenParser(new Project_Set_TokenParser()); </pre></div></td></tr></table> ### Defining a Token Parser Now, let's see the actual code of this class: <table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre> 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20</pre></div></td><td class="code"><div class="highlight"><pre>class Project_Set_TokenParser extends Twig_TokenParser { public function parse(Twig_Token $token) { $parser = $this-&gt;parser; $stream = $parser-&gt;getStream(); $name = $stream-&gt;expect(Twig_Token::NAME_TYPE)-&gt;getValue(); $stream-&gt;expect(Twig_Token::OPERATOR_TYPE, '='); $value = $parser-&gt;getExpressionParser()-&gt;parseExpression(); $stream-&gt;expect(Twig_Token::BLOCK_END_TYPE); return new Project_Set_Node($name, $value, $token-&gt;getLine(), $this-&gt;getTag()); } public function getTag() { return 'set'; } } </pre></div></td></tr></table> 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 callfrom 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 whetherthe current token is of a particular type or value (or both). The value may be anarray of several possible values. - `expect($type[, $value[, $message]])`: If the current token isn't of the giventype/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 forthe `set` tag. Tip Reading the existing `TokenParser` classes is the best way to learn allthe nitty-gritty details of the parsing process. ### Defining a Node The `Project_Set_Node` class itself is rather simple: <table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre> 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17</pre></div></td><td class="code"><div class="highlight"><pre>class Project_Set_Node extends Twig_Node { public function __construct($name, Twig_Node_Expression $value, $line, $tag = null) { parent::__construct(array('value' =&gt; $value), array('name' =&gt; $name), $line, $tag); } public function compile(Twig_Compiler $compiler) { $compiler -&gt;addDebugInfo($this) -&gt;write('$context[\''.$this-&gt;getAttribute('name').'\'] = ') -&gt;subcompile($this-&gt;getNode('value')) -&gt;raw(";\n") ; } } </pre></div></td></tr></table> The compiler implements a fluid interface and provides methods that helps thedeveloper 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 beginningof 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 tothe current node as a comment. - `indent()`: Indents the generated code (see `Twig_Node_Block` for ausage example). - `outdent()`: Outdents the generated code (see `Twig_Node_Block` for ausage example). ### Creating an Extension The main motivation for writing an extension is to move often used code into areusable class like adding support for internationalization. An extension candefine tags, filters, tests, operators, global variables, functions, and nodevisitors. Creating an extension also makes for a better separation of code that isexecuted at compilation time and code needed at runtime. As such, it makesyour 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 torecompile your templates whenever you make a change to it (when`auto_reload` is enabled). Note Before writing your own extensions, have a look at the Twig officialextension repository: [http://github.com/twigphp/Twig-extensions](http://github.com/twigphp/Twig-extensions). An extension is a class that implements the following interface: <table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre> 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71</pre></div></td><td class="code"><div class="highlight"><pre>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 * * @deprecated since 1.23 (to be removed in 2.0), implement Twig_Extension_InitRuntimeInterface instead */ 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 * * @deprecated since 1.23 (to be removed in 2.0), implement Twig_Extension_GlobalsInterface instead */ function getGlobals(); /** * Returns the name of the extension. * * @return string The extension name */ function getName(); } </pre></div></td></tr></table> To keep your extension class clean and lean, it can inherit from the built-in`Twig_Extension` class instead of implementing the whole interface. Thatway, 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 extensionpossible: <table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1 2 3 4 5 6 7</pre></div></td><td class="code"><div class="highlight"><pre>class Project_Twig_Extension extends Twig_Extension { public function getName() { return 'project'; } } </pre></div></td></tr></table> Note Of course, this extension does nothing for now. We will customize it inthe next sections. Twig does not care where you save your extension on the filesystem, as allextensions must be registered explicitly to be available in your templates. You can register an extension by using the `addExtension()` method on yourmain `Environment` object: <table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1 2</pre></div></td><td class="code"><div class="highlight"><pre>$twig = new Twig_Environment($loader); $twig-&gt;addExtension(new Project_Twig_Extension()); </pre></div></td></tr></table> Tip The bundled extensions are great examples of how extensions work. ### Globals Global variables can be registered in an extension via the `getGlobals()`method: <table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre> 1 2 3 4 5 6 7 8 9 10 11</pre></div></td><td class="code"><div class="highlight"><pre>class Project_Twig_Extension extends Twig_Extension { public function getGlobals() { return array( 'text' =&gt; new Text(), ); } // ... } </pre></div></td></tr></table> ### Functions Functions can be registered in an extension via the `getFunctions()`method: <table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre> 1 2 3 4 5 6 7 8 9 10 11</pre></div></td><td class="code"><div class="highlight"><pre>class Project_Twig_Extension extends Twig_Extension { public function getFunctions() { return array( new Twig_SimpleFunction('lipsum', 'generate_lipsum'), ); } // ... } </pre></div></td></tr></table> ### 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 Twigenvironment: <table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre> 1 2 3 4 5 6 7 8 9 10 11</pre></div></td><td class="code"><div class="highlight"><pre>class Project_Twig_Extension extends Twig_Extension { public function getFilters() { return array( new Twig_SimpleFilter('rot13', 'str_rot13'), ); } // ... } </pre></div></td></tr></table> ### Tags Adding a tag in an extension can be done by overriding the`getTokenParsers()` method. This method must return an array of tags to addto the Twig environment: <table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1 2 3 4 5 6 7 8 9</pre></div></td><td class="code"><div class="highlight"><pre>class Project_Twig_Extension extends Twig_Extension { public function getTokenParsers() { return array(new Project_Set_TokenParser()); } // ... } </pre></div></td></tr></table> In the above code, we have added a single new tag, defined by the`Project_Set_TokenParser` class. The `Project_Set_TokenParser` class isresponsible for parsing the tag and compiling it to PHP. ### Operators The `getOperators()` methods lets you add new operators. Here is how to add`!`, `||`, and `&&` operators: <table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre> 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17</pre></div></td><td class="code"><div class="highlight"><pre>class Project_Twig_Extension extends Twig_Extension { public function getOperators() { return array( array( '!' =&gt; array('precedence' =&gt; 50, 'class' =&gt; 'Twig_Node_Expression_Unary_Not'), ), array( '||' =&gt; array('precedence' =&gt; 10, 'class' =&gt; 'Twig_Node_Expression_Binary_Or', 'associativity' =&gt; Twig_ExpressionParser::OPERATOR_LEFT), '&amp;&amp;' =&gt; array('precedence' =&gt; 15, 'class' =&gt; 'Twig_Node_Expression_Binary_And', 'associativity' =&gt; Twig_ExpressionParser::OPERATOR_LEFT), ), ); } // ... } </pre></div></td></tr></table> ### Tests The `getTests()` method lets you add new test functions: <table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre> 1 2 3 4 5 6 7 8 9 10 11</pre></div></td><td class="code"><div class="highlight"><pre>class Project_Twig_Extension extends Twig_Extension { public function getTests() { return array( new Twig_SimpleTest('even', 'twig_test_even'), ); } // ... } </pre></div></td></tr></table> ### Overloading To overload an already defined filter, test, operator, global variable, orfunction, re-define it in an extension and register it **as late aspossible** (order matters): <table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre> 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22</pre></div></td><td class="code"><div class="highlight"><pre>class MyCoreExtension extends Twig_Extension { public function getFilters() { return array( new Twig_SimpleFilter('date', array($this, 'dateFilter')), ); } public function dateFilter($timestamp, $format = 'F j, Y H:i') { // do something different from the built-in date filter } public function getName() { return 'project'; } } $twig = new Twig_Environment($loader); $twig-&gt;addExtension(new MyCoreExtension()); </pre></div></td></tr></table> Here, we have overloaded the built-in `date` filter with a custom one. If you do the same on the Twig_Environment itself, beware that it takesprecedence over any other registered extensions: <table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre>1 2 3 4 5 6 7</pre></div></td><td class="code"><div class="highlight"><pre>$twig = new Twig_Environment($loader); $twig-&gt;addFilter(new Twig_SimpleFilter('date', function ($timestamp, $format = 'F j, Y H:i') { // do something different from the built-in date filter })); // the date filter will come from the above registration, not // from the registered extension below $twig-&gt;addExtension(new MyCoreExtension()); </pre></div></td></tr></table> Caution Note that overloading the built-in Twig elements is not recommended as itmight be confusing. ### Testing an Extension ### Functional Tests You can create functional tests for extensions simply by creating thefollowing file structure in your test directory: <table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre> 1 2 3 4 5 6 7 8 9 10 11</pre></div></td><td class="code"><div class="highlight"><pre>Fixtures/ filters/ foo.test bar.test functions/ foo.test bar.test tags/ foo.test bar.test IntegrationTest.php </pre></div></td></tr></table> The `IntegrationTest.php` file should look like this: <table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre> 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15</pre></div></td><td class="code"><div class="highlight"><pre>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/'; } } </pre></div></td></tr></table> Fixtures examples can be found within the Twig repository[tests/Twig/Fixtures](https://github.com/twigphp/Twig/tree/master/test/Twig/Tests/Fixtures) [https://github.com/twigphp/Twig/tree/master/test/Twig/Tests/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](https://github.com/twigphp/Twig/tree/master/test/Twig/Tests/Node) [https://github.com/twigphp/Twig/tree/master/test/Twig/Tests/Node] directory.