advanced.rst 27KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891
  1. Extending Twig
  2. ==============
  3. Twig can be extended in many ways; you can add extra tags, filters, tests,
  4. operators, global variables, and functions. You can even extend the parser
  5. itself with node visitors.
  6. .. note::
  7. The first section of this chapter describes how to extend Twig easily. If
  8. you want to reuse your changes in different projects or if you want to
  9. share them with others, you should then create an extension as described
  10. in the following section.
  11. .. caution::
  12. When extending Twig by calling methods on the Twig environment instance,
  13. Twig won't be able to recompile your templates when the PHP code is
  14. updated. To see your changes in real-time, either disable template caching
  15. or package your code into an extension (see the next section of this
  16. chapter).
  17. Before extending Twig, you must understand the differences between all the
  18. different possible extension points and when to use them.
  19. First, remember that Twig has two main language constructs:
  20. * ``{{ }}``: used to print the result of an expression evaluation;
  21. * ``{% %}``: used to execute statements.
  22. To understand why Twig exposes so many extension points, let's see how to
  23. implement a *Lorem ipsum* generator (it needs to know the number of words to
  24. generate).
  25. You can use a ``lipsum`` *tag*:
  26. .. code-block:: jinja
  27. {% lipsum 40 %}
  28. That works, but using a tag for ``lipsum`` is not a good idea for at least
  29. three main reasons:
  30. * ``lipsum`` is not a language construct;
  31. * The tag outputs something;
  32. * The tag is not flexible as you cannot use it in an expression:
  33. .. code-block:: jinja
  34. {{ 'some text' ~ {% lipsum 40 %} ~ 'some more text' }}
  35. In fact, you rarely need to create tags; and that's good news because tags are
  36. the most complex extension point of Twig.
  37. Now, let's use a ``lipsum`` *filter*:
  38. .. code-block:: jinja
  39. {{ 40|lipsum }}
  40. Again, it works, but it looks weird. A filter transforms the passed value to
  41. something else but here we use the value to indicate the number of words to
  42. generate (so, ``40`` is an argument of the filter, not the value we want to
  43. transform).
  44. Next, let's use a ``lipsum`` *function*:
  45. .. code-block:: jinja
  46. {{ lipsum(40) }}
  47. Here we go. For this specific example, the creation of a function is the
  48. extension point to use. And you can use it anywhere an expression is accepted:
  49. .. code-block:: jinja
  50. {{ 'some text' ~ ipsum(40) ~ 'some more text' }}
  51. {% set ipsum = ipsum(40) %}
  52. Last but not the least, you can also use a *global* object with a method able
  53. to generate lorem ipsum text:
  54. .. code-block:: jinja
  55. {{ text.lipsum(40) }}
  56. As a rule of thumb, use functions for frequently used features and global
  57. objects for everything else.
  58. Keep in mind the following when you want to extend Twig:
  59. ========== ========================== ========== =========================
  60. What? Implementation difficulty? How often? When?
  61. ========== ========================== ========== =========================
  62. *macro* trivial frequent Content generation
  63. *global* trivial frequent Helper object
  64. *function* trivial frequent Content generation
  65. *filter* trivial frequent Value transformation
  66. *tag* complex rare DSL language construct
  67. *test* trivial rare Boolean decision
  68. *operator* trivial rare Values transformation
  69. ========== ========================== ========== =========================
  70. Globals
  71. -------
  72. A global variable is like any other template variable, except that it's
  73. available in all templates and macros::
  74. $twig = new Twig_Environment($loader);
  75. $twig->addGlobal('text', new Text());
  76. You can then use the ``text`` variable anywhere in a template:
  77. .. code-block:: jinja
  78. {{ text.lipsum(40) }}
  79. Filters
  80. -------
  81. A filter is a regular PHP function or an object method that takes the left
  82. side of the filter (before the pipe ``|``) as first argument and the extra
  83. arguments passed to the filter (within parentheses ``()``) as extra arguments.
  84. Defining a filter is as easy as associating the filter name with a PHP
  85. callable. For instance, let's say you have the following code in a template:
  86. .. code-block:: jinja
  87. {{ 'TWIG'|lower }}
  88. When compiling this template to PHP, Twig looks for the PHP callable
  89. associated with the ``lower`` filter. The ``lower`` filter is a built-in Twig
  90. filter, and it is simply mapped to the PHP ``strtolower()`` function. After
  91. compilation, the generated PHP code is roughly equivalent to:
  92. .. code-block:: html+php
  93. <?php echo strtolower('TWIG') ?>
  94. As you can see, the ``'TWIG'`` string is passed as a first argument to the PHP
  95. function.
  96. A filter can also take extra arguments like in the following example:
  97. .. code-block:: jinja
  98. {{ now|date('d/m/Y') }}
  99. In this case, the extra arguments are passed to the function after the main
  100. argument, and the compiled code is equivalent to:
  101. .. code-block:: html+php
  102. <?php echo twig_date_format_filter($now, 'd/m/Y') ?>
  103. Let's see how to create a new filter.
  104. In this section, we will create a ``rot13`` filter, which should return the
  105. `rot13`_ transformation of a string. Here is an example of its usage and the
  106. expected output:
  107. .. code-block:: jinja
  108. {{ "Twig"|rot13 }}
  109. {# should displays Gjvt #}
  110. Adding a filter is as simple as calling the ``addFilter()`` method on the
  111. ``Twig_Environment`` instance::
  112. $twig = new Twig_Environment($loader);
  113. $twig->addFilter('rot13', new Twig_Filter_Function('str_rot13'));
  114. The second argument of ``addFilter()`` is an instance of ``Twig_Filter``.
  115. Here, we use ``Twig_Filter_Function`` as the filter is a PHP function. The
  116. first argument passed to the ``Twig_Filter_Function`` constructor is the name
  117. of the PHP function to call, here ``str_rot13``, a native PHP function.
  118. Let's say I now want to be able to add a prefix before the converted string:
  119. .. code-block:: jinja
  120. {{ "Twig"|rot13('prefix_') }}
  121. {# should displays prefix_Gjvt #}
  122. As the PHP ``str_rot13()`` function does not support this requirement, let's
  123. create a new PHP function::
  124. function project_compute_rot13($string, $prefix = '')
  125. {
  126. return $prefix.str_rot13($string);
  127. }
  128. As you can see, the ``prefix`` argument of the filter is passed as an extra
  129. argument to the ``project_compute_rot13()`` function.
  130. Adding this filter is as easy as before::
  131. $twig->addFilter('rot13', new Twig_Filter_Function('project_compute_rot13'));
  132. For better encapsulation, a filter can also be defined as a static method of a
  133. class. The ``Twig_Filter_Function`` class can also be used to register such
  134. static methods as filters::
  135. $twig->addFilter('rot13', new Twig_Filter_Function('SomeClass::rot13Filter'));
  136. .. tip::
  137. In an extension, you can also define a filter as a static method of the
  138. extension class.
  139. Environment aware Filters
  140. ~~~~~~~~~~~~~~~~~~~~~~~~~
  141. The ``Twig_Filter`` classes take options as their last argument. For instance,
  142. if you want access to the current environment instance in your filter, set the
  143. ``needs_environment`` option to ``true``::
  144. $filter = new Twig_Filter_Function('str_rot13', array('needs_environment' => true));
  145. Twig will then pass the current environment as the first argument to the
  146. filter call::
  147. function twig_compute_rot13(Twig_Environment $env, $string)
  148. {
  149. // get the current charset for instance
  150. $charset = $env->getCharset();
  151. return str_rot13($string);
  152. }
  153. Automatic Escaping
  154. ~~~~~~~~~~~~~~~~~~
  155. If automatic escaping is enabled, the output of the filter may be escaped
  156. before printing. If your filter acts as an escaper (or explicitly outputs html
  157. or javascript code), you will want the raw output to be printed. In such a
  158. case, set the ``is_safe`` option::
  159. $filter = new Twig_Filter_Function('nl2br', array('is_safe' => array('html')));
  160. Some filters may need to work on input that is already escaped or safe, for
  161. example when adding (safe) html tags to originally unsafe output. In such a
  162. case, set the ``pre_escape`` option to escape the input data before it is run
  163. through your filter::
  164. $filter = new Twig_Filter_Function('somefilter', array('pre_escape' => 'html', 'is_safe' => array('html')));
  165. Dynamic Filters
  166. ~~~~~~~~~~~~~~~
  167. .. versionadded:: 1.5
  168. Dynamic filters support was added in Twig 1.5.
  169. A filter name containing the special ``*`` character is a dynamic filter as
  170. the ``*`` can be any string::
  171. $twig->addFilter('*_path', new Twig_Filter_Function('twig_path'));
  172. function twig_path($name, $arguments)
  173. {
  174. // ...
  175. }
  176. The following filters will be matched by the above defined dynamic filter:
  177. * ``product_path``
  178. * ``category_path``
  179. A dynamic filter can define more than one dynamic parts::
  180. $twig->addFilter('*_path_*', new Twig_Filter_Function('twig_path'));
  181. function twig_path($name, $suffix, $arguments)
  182. {
  183. // ...
  184. }
  185. The filter will receive all dynamic part values before the normal filters
  186. arguments. For instance, a call to ``'foo'|a_path_b()`` will result in the
  187. following PHP call: ``twig_path('a', 'b', 'foo')``.
  188. Functions
  189. ---------
  190. A function is a regular PHP function or an object method that can be called from
  191. templates.
  192. .. code-block:: jinja
  193. {{ constant("DATE_W3C") }}
  194. When compiling this template to PHP, Twig looks for the PHP callable
  195. associated with the ``constant`` function. The ``constant`` function is a built-in Twig
  196. function, and it is simply mapped to the PHP ``constant()`` function. After
  197. compilation, the generated PHP code is roughly equivalent to:
  198. .. code-block:: html+php
  199. <?php echo constant('DATE_W3C') ?>
  200. Adding a function is similar to adding a filter. This can be done by calling the
  201. ``addFunction()`` method on the ``Twig_Environment`` instance::
  202. $twig = new Twig_Environment($loader);
  203. $twig->addFunction('functionName', new Twig_Function_Function('someFunction'));
  204. You can also expose extension methods as functions in your templates::
  205. // $this is an object that implements Twig_ExtensionInterface.
  206. $twig = new Twig_Environment($loader);
  207. $twig->addFunction('otherFunction', new Twig_Function_Method($this, 'someMethod'));
  208. Functions also support ``needs_environment`` and ``is_safe`` parameters.
  209. Dynamic Functions
  210. ~~~~~~~~~~~~~~~~~
  211. .. versionadded:: 1.5
  212. Dynamic functions support was added in Twig 1.5.
  213. A function name containing the special ``*`` character is a dynamic function
  214. as the ``*`` can be any string::
  215. $twig->addFunction('*_path', new Twig_Function_Function('twig_path'));
  216. function twig_path($name, $arguments)
  217. {
  218. // ...
  219. }
  220. The following functions will be matched by the above defined dynamic function:
  221. * ``product_path``
  222. * ``category_path``
  223. A dynamic function can define more than one dynamic parts::
  224. $twig->addFilter('*_path_*', new Twig_Filter_Function('twig_path'));
  225. function twig_path($name, $suffix, $arguments)
  226. {
  227. // ...
  228. }
  229. The function will receive all dynamic part values before the normal functions
  230. arguments. For instance, a call to ``a_path_b('foo')`` will result in the
  231. following PHP call: ``twig_path('a', 'b', 'foo')``.
  232. Tags
  233. ----
  234. One of the most exciting feature of a template engine like Twig is the
  235. possibility to define new language constructs. This is also the most complex
  236. feature as you need to understand how Twig's internals work.
  237. Let's create a simple ``set`` tag that allows the definition of simple
  238. variables from within a template. The tag can be used like follows:
  239. .. code-block:: jinja
  240. {% set name = "value" %}
  241. {{ name }}
  242. {# should output value #}
  243. .. note::
  244. The ``set`` tag is part of the Core extension and as such is always
  245. available. The built-in version is slightly more powerful and supports
  246. multiple assignments by default (cf. the template designers chapter for
  247. more information).
  248. Three steps are needed to define a new tag:
  249. * Defining a Token Parser class (responsible for parsing the template code);
  250. * Defining a Node class (responsible for converting the parsed code to PHP);
  251. * Registering the tag.
  252. Registering a new tag
  253. ~~~~~~~~~~~~~~~~~~~~~
  254. Adding a tag is as simple as calling the ``addTokenParser`` method on the
  255. ``Twig_Environment`` instance::
  256. $twig = new Twig_Environment($loader);
  257. $twig->addTokenParser(new Project_Set_TokenParser());
  258. Defining a Token Parser
  259. ~~~~~~~~~~~~~~~~~~~~~~~
  260. Now, let's see the actual code of this class::
  261. class Project_Set_TokenParser extends Twig_TokenParser
  262. {
  263. public function parse(Twig_Token $token)
  264. {
  265. $lineno = $token->getLine();
  266. $name = $this->parser->getStream()->expect(Twig_Token::NAME_TYPE)->getValue();
  267. $this->parser->getStream()->expect(Twig_Token::OPERATOR_TYPE, '=');
  268. $value = $this->parser->getExpressionParser()->parseExpression();
  269. $this->parser->getStream()->expect(Twig_Token::BLOCK_END_TYPE);
  270. return new Project_Set_Node($name, $value, $lineno, $this->getTag());
  271. }
  272. public function getTag()
  273. {
  274. return 'set';
  275. }
  276. }
  277. The ``getTag()`` method must return the tag we want to parse, here ``set``.
  278. The ``parse()`` method is invoked whenever the parser encounters a ``set``
  279. tag. It should return a ``Twig_Node`` instance that represents the node (the
  280. ``Project_Set_Node`` calls creating is explained in the next section).
  281. The parsing process is simplified thanks to a bunch of methods you can call
  282. from the token stream (``$this->parser->getStream()``):
  283. * ``getCurrent()``: Gets the current token in the stream.
  284. * ``next()``: Moves to the next token in the stream, *but returns the old one*.
  285. * ``test($type)``, ``test($value)`` or ``test($type, $value)``: Determines whether
  286. the current token is of a particular type or value (or both). The value may be an
  287. array of several possible values.
  288. * ``expect($type[, $value[, $message]])``: If the current token isn't of the given
  289. type/value a syntax error is thrown. Otherwise, if the type and value are correct,
  290. the token is returned and the stream moves to the next token.
  291. * ``look()``: Looks a the next token without consuming it.
  292. Parsing expressions is done by calling the ``parseExpression()`` like we did for
  293. the ``set`` tag.
  294. .. tip::
  295. Reading the existing ``TokenParser`` classes is the best way to learn all
  296. the nitty-gritty details of the parsing process.
  297. Defining a Node
  298. ~~~~~~~~~~~~~~~
  299. The ``Project_Set_Node`` class itself is rather simple::
  300. class Project_Set_Node extends Twig_Node
  301. {
  302. public function __construct($name, Twig_Node_Expression $value, $lineno, $tag = null)
  303. {
  304. parent::__construct(array('value' => $value), array('name' => $name), $lineno, $tag);
  305. }
  306. public function compile(Twig_Compiler $compiler)
  307. {
  308. $compiler
  309. ->addDebugInfo($this)
  310. ->write('$context[\''.$this->getAttribute('name').'\'] = ')
  311. ->subcompile($this->getNode('value'))
  312. ->raw(";\n")
  313. ;
  314. }
  315. }
  316. The compiler implements a fluid interface and provides methods that helps the
  317. developer generate beautiful and readable PHP code:
  318. * ``subcompile()``: Compiles a node.
  319. * ``raw()``: Writes the given string as is.
  320. * ``write()``: Writes the given string by adding indentation at the beginning
  321. of each line.
  322. * ``string()``: Writes a quoted string.
  323. * ``repr()``: Writes a PHP representation of a given value (see
  324. ``Twig_Node_For`` for a usage example).
  325. * ``addDebugInfo()``: Adds the line of the original template file related to
  326. the current node as a comment.
  327. * ``indent()``: Indents the generated code (see ``Twig_Node_Block`` for a
  328. usage example).
  329. * ``outdent()``: Outdents the generated code (see ``Twig_Node_Block`` for a
  330. usage example).
  331. .. _creating_extensions:
  332. Creating an Extension
  333. ---------------------
  334. The main motivation for writing an extension is to move often used code into a
  335. reusable class like adding support for internationalization. An extension can
  336. define tags, filters, tests, operators, global variables, functions, and node
  337. visitors.
  338. Creating an extension also makes for a better separation of code that is
  339. executed at compilation time and code needed at runtime. As such, it makes
  340. your code faster.
  341. Most of the time, it is useful to create a single extension for your project,
  342. to host all the specific tags and filters you want to add to Twig.
  343. .. tip::
  344. When packaging your code into an extension, Twig is smart enough to
  345. recompile your templates whenever you make a change to it (when the
  346. ``auto_reload`` is enabled).
  347. .. note::
  348. Before writing your own extensions, have a look at the Twig official
  349. extension repository: http://github.com/fabpot/Twig-extensions.
  350. An extension is a class that implements the following interface::
  351. interface Twig_ExtensionInterface
  352. {
  353. /**
  354. * Initializes the runtime environment.
  355. *
  356. * This is where you can load some file that contains filter functions for instance.
  357. *
  358. * @param Twig_Environment $environment The current Twig_Environment instance
  359. */
  360. function initRuntime(Twig_Environment $environment);
  361. /**
  362. * Returns the token parser instances to add to the existing list.
  363. *
  364. * @return array An array of Twig_TokenParserInterface or Twig_TokenParserBrokerInterface instances
  365. */
  366. function getTokenParsers();
  367. /**
  368. * Returns the node visitor instances to add to the existing list.
  369. *
  370. * @return array An array of Twig_NodeVisitorInterface instances
  371. */
  372. function getNodeVisitors();
  373. /**
  374. * Returns a list of filters to add to the existing list.
  375. *
  376. * @return array An array of filters
  377. */
  378. function getFilters();
  379. /**
  380. * Returns a list of tests to add to the existing list.
  381. *
  382. * @return array An array of tests
  383. */
  384. function getTests();
  385. /**
  386. * Returns a list of functions to add to the existing list.
  387. *
  388. * @return array An array of functions
  389. */
  390. function getFunctions();
  391. /**
  392. * Returns a list of operators to add to the existing list.
  393. *
  394. * @return array An array of operators
  395. */
  396. function getOperators();
  397. /**
  398. * Returns a list of global variables to add to the existing list.
  399. *
  400. * @return array An array of global variables
  401. */
  402. function getGlobals();
  403. /**
  404. * Returns the name of the extension.
  405. *
  406. * @return string The extension name
  407. */
  408. function getName();
  409. }
  410. To keep your extension class clean and lean, it can inherit from the built-in
  411. ``Twig_Extension`` class instead of implementing the whole interface. That
  412. way, you just need to implement the ``getName()`` method as the
  413. ``Twig_Extension`` provides empty implementations for all other methods.
  414. The ``getName()`` method must return a unique identifier for your extension.
  415. Now, with this information in mind, let's create the most basic extension
  416. possible::
  417. class Project_Twig_Extension extends Twig_Extension
  418. {
  419. public function getName()
  420. {
  421. return 'project';
  422. }
  423. }
  424. .. note::
  425. Of course, this extension does nothing for now. We will customize it in
  426. the next sections.
  427. Twig does not care where you save your extension on the filesystem, as all
  428. extensions must be registered explicitly to be available in your templates.
  429. You can register an extension by using the ``addExtension()`` method on your
  430. main ``Environment`` object::
  431. $twig = new Twig_Environment($loader);
  432. $twig->addExtension(new Project_Twig_Extension());
  433. Of course, you need to first load the extension file by either using
  434. ``require_once()`` or by using an autoloader (see `spl_autoload_register()`_).
  435. .. tip::
  436. The bundled extensions are great examples of how extensions work.
  437. Globals
  438. ~~~~~~~
  439. Global variables can be registered in an extension via the ``getGlobals()``
  440. method::
  441. class Project_Twig_Extension extends Twig_Extension
  442. {
  443. public function getGlobals()
  444. {
  445. return array(
  446. 'text' => new Text(),
  447. );
  448. }
  449. // ...
  450. }
  451. Functions
  452. ~~~~~~~~~
  453. Functions can be registered in an extension via the ``getFunctions()``
  454. method::
  455. class Project_Twig_Extension extends Twig_Extension
  456. {
  457. public function getFunctions()
  458. {
  459. return array(
  460. 'lipsum' => new Twig_Function_Function('generate_lipsum'),
  461. );
  462. }
  463. // ...
  464. }
  465. Filters
  466. ~~~~~~~
  467. To add a filter to an extension, you need to override the ``getFilters()``
  468. method. This method must return an array of filters to add to the Twig
  469. environment::
  470. class Project_Twig_Extension extends Twig_Extension
  471. {
  472. public function getFilters()
  473. {
  474. return array(
  475. 'rot13' => new Twig_Filter_Function('str_rot13'),
  476. );
  477. }
  478. // ...
  479. }
  480. As you can see in the above code, the ``getFilters()`` method returns an array
  481. where keys are the name of the filters (``rot13``) and the values the
  482. definition of the filter (``new Twig_Filter_Function('str_rot13')``).
  483. As seen in the previous chapter, you can also define filters as static methods
  484. on the extension class::
  485. $twig->addFilter('rot13', new Twig_Filter_Function('Project_Twig_Extension::rot13Filter'));
  486. You can also use ``Twig_Filter_Method`` instead of ``Twig_Filter_Function``
  487. when defining a filter to use a method::
  488. class Project_Twig_Extension extends Twig_Extension
  489. {
  490. public function getFilters()
  491. {
  492. return array(
  493. 'rot13' => new Twig_Filter_Method($this, 'rot13Filter'),
  494. );
  495. }
  496. public function rot13Filter($string)
  497. {
  498. return str_rot13($string);
  499. }
  500. // ...
  501. }
  502. The first argument of the ``Twig_Filter_Method`` constructor is always
  503. ``$this``, the current extension object. The second one is the name of the
  504. method to call.
  505. Using methods for filters is a great way to package your filter without
  506. polluting the global namespace. This also gives the developer more flexibility
  507. at the cost of a small overhead.
  508. Overriding default Filters
  509. ..........................
  510. If some default core filters do not suit your needs, you can easily override
  511. them by creating your own core extension. Of course, you don't need to copy
  512. and paste the whole core extension code of Twig. Instead, you can just extends
  513. it and override the filter(s) you want by overriding the ``getFilters()``
  514. method::
  515. class MyCoreExtension extends Twig_Extension_Core
  516. {
  517. public function getFilters()
  518. {
  519. return array_merge(parent::getFilters(), array(
  520. 'date' => new Twig_Filter_Method($this, 'dateFilter'),
  521. // ...
  522. ));
  523. }
  524. public function dateFilter($timestamp, $format = 'F j, Y H:i')
  525. {
  526. return '...'.twig_date_format_filter($timestamp, $format);
  527. }
  528. // ...
  529. }
  530. Here, we override the ``date`` filter with a custom one. Using this new core
  531. extension is as simple as registering the ``MyCoreExtension`` extension by
  532. calling the ``addExtension()`` method on the environment instance::
  533. $twig = new Twig_Environment($loader);
  534. $twig->addExtension(new MyCoreExtension());
  535. But I can already hear some people wondering how it can work as the Core
  536. extension is loaded by default. That's true, but the trick is that both
  537. extensions share the same unique identifier (``core`` - defined in the
  538. ``getName()`` method). By registering an extension with the same name as an
  539. existing one, you have actually overridden the default one, even if it is
  540. already registered::
  541. $twig->addExtension(new Twig_Extension_Core());
  542. $twig->addExtension(new MyCoreExtension());
  543. Tags
  544. ~~~~
  545. Adding a tag in an extension can be done by overriding the
  546. ``getTokenParsers()`` method. This method must return an array of tags to add
  547. to the Twig environment::
  548. class Project_Twig_Extension extends Twig_Extension
  549. {
  550. public function getTokenParsers()
  551. {
  552. return array(new Project_Set_TokenParser());
  553. }
  554. // ...
  555. }
  556. In the above code, we have added a single new tag, defined by the
  557. ``Project_Set_TokenParser`` class. The ``Project_Set_TokenParser`` class is
  558. responsible for parsing the tag and compiling it to PHP.
  559. Operators
  560. ~~~~~~~~~
  561. The ``getOperators()`` methods allows to add new operators. Here is how to add
  562. ``!``, ``||``, and ``&&`` operators::
  563. class Project_Twig_Extension extends Twig_Extension
  564. {
  565. public function getOperators()
  566. {
  567. return array(
  568. array(
  569. '!' => array('precedence' => 50, 'class' => 'Twig_Node_Expression_Unary_Not'),
  570. ),
  571. array(
  572. '||' => array('precedence' => 10, 'class' => 'Twig_Node_Expression_Binary_Or', 'associativity' => Twig_ExpressionParser::OPERATOR_LEFT),
  573. '&&' => array('precedence' => 15, 'class' => 'Twig_Node_Expression_Binary_And', 'associativity' => Twig_ExpressionParser::OPERATOR_LEFT),
  574. ),
  575. );
  576. }
  577. // ...
  578. }
  579. Tests
  580. ~~~~~
  581. The ``getTests()`` methods allows to add new test functions::
  582. class Project_Twig_Extension extends Twig_Extension
  583. {
  584. public function getTests()
  585. {
  586. return array(
  587. 'even' => new Twig_Test_Function('twig_test_even'),
  588. );
  589. }
  590. // ...
  591. }
  592. Testing an Extension
  593. --------------------
  594. .. versionadded:: 1.10
  595. Support for functional tests was added in Twig 1.10.
  596. Functional Tests
  597. ~~~~~~~~~~~~~~~~
  598. You can create functional tests for extensions simply by creating the
  599. following file structure in your test directory::
  600. Fixtures/
  601. filters/
  602. foo.test
  603. bar.test
  604. functions/
  605. foo.test
  606. bar.test
  607. tags/
  608. foo.test
  609. bar.test
  610. IntegrationTest.php
  611. The ``IntegrationTest.php`` file should look like this::
  612. class Project_Tests_IntegrationTest extends Twig_Test_IntegrationTestCase
  613. {
  614. public function getExtensions()
  615. {
  616. return array(
  617. new Project_Twig_Extension1(),
  618. new Project_Twig_Extension2(),
  619. );
  620. }
  621. public function getFixturesDir()
  622. {
  623. return dirname(__FILE__).'/Fixtures/';
  624. }
  625. }
  626. Fixtures examples can be found within the Twig repository
  627. `tests/Twig/Fixtures`_ directory.
  628. Node Tests
  629. ~~~~~~~~~~
  630. Testing the node visitors can be complex, so extend your test cases from
  631. ``Twig_Test_NodeTestCase``. Examples can be found in the Twig repository
  632. `tests/Twig/Node`_ directory.
  633. .. _`spl_autoload_register()`: http://www.php.net/spl_autoload_register
  634. .. _`rot13`: http://www.php.net/manual/en/function.str-rot13.php
  635. .. _`tests/Twig/Fixtures`: https://github.com/fabpot/Twig/tree/master/test/Twig/Tests/Fixtures
  636. .. _`tests/Twig/Node`: https://github.com/fabpot/Twig/tree/master/test/Twig/Tests/Node