extensions.rst 9.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. Creating a Twig Extension
  2. =========================
  3. The main motivation for writing an extension is to move often used code into a
  4. reusable class like adding support for internationalization. An extension can
  5. define tags, filters, tests, operators, global variables, functions, and node
  6. visitors.
  7. Creating an extension also makes for a better separation of code that is
  8. executed at compilation time and code needed at runtime. As such, it makes
  9. your code faster.
  10. Most of the time, it is useful to create a single extension for your project,
  11. to host all the specific tags and filters you want to add to Twig.
  12. .. note::
  13. Before writing your own extensions, have a look at the Twig official
  14. extension repository: http://github.com/fabpot/Twig-extensions.
  15. An extension is a class that implements the following interface::
  16. interface Twig_ExtensionInterface
  17. {
  18. /**
  19. * Initializes the runtime environment.
  20. *
  21. * This is where you can load some file that contains filter functions for instance.
  22. *
  23. * @param Twig_Environment $environment The current Twig_Environment instance
  24. */
  25. function initRuntime(Twig_Environment $environment);
  26. /**
  27. * Returns the token parser instances to add to the existing list.
  28. *
  29. * @return array An array of Twig_TokenParserInterface or Twig_TokenParserBrokerInterface instances
  30. */
  31. function getTokenParsers();
  32. /**
  33. * Returns the node visitor instances to add to the existing list.
  34. *
  35. * @return array An array of Twig_NodeVisitorInterface instances
  36. */
  37. function getNodeVisitors();
  38. /**
  39. * Returns a list of filters to add to the existing list.
  40. *
  41. * @return array An array of filters
  42. */
  43. function getFilters();
  44. /**
  45. * Returns a list of tests to add to the existing list.
  46. *
  47. * @return array An array of tests
  48. */
  49. function getTests();
  50. /**
  51. * Returns a list of functions to add to the existing list.
  52. *
  53. * @return array An array of functions
  54. */
  55. function getFunctions();
  56. /**
  57. * Returns a list of operators to add to the existing list.
  58. *
  59. * @return array An array of operators
  60. */
  61. function getOperators();
  62. /**
  63. * Returns a list of global variables to add to the existing list.
  64. *
  65. * @return array An array of global variables
  66. */
  67. function getGlobals();
  68. /**
  69. * Returns the name of the extension.
  70. *
  71. * @return string The extension name
  72. */
  73. function getName();
  74. }
  75. To keep your extension class clean and lean, it can inherit from the built-in
  76. ``Twig_Extension`` class instead of implementing the whole interface. That
  77. way, you just need to implement the ``getName()`` method as the
  78. ``Twig_Extension`` provides empty implementations for all other methods.
  79. The ``getName()`` method must return a unique identifier for your extension.
  80. Now, with this information in mind, let's create the most basic extension
  81. possible::
  82. class Project_Twig_Extension extends Twig_Extension
  83. {
  84. public function getName()
  85. {
  86. return 'project';
  87. }
  88. }
  89. .. note::
  90. Of course, this extension does nothing for now. We will customize it in
  91. the next sections.
  92. Twig does not care where you save your extension on the filesystem, as all
  93. extensions must be registered explicitly to be available in your templates.
  94. You can register an extension by using the ``addExtension()`` method on your
  95. main ``Environment`` object::
  96. $twig = new Twig_Environment($loader);
  97. $twig->addExtension(new Project_Twig_Extension());
  98. Of course, you need to first load the extension file by either using
  99. ``require_once()`` or by using an autoloader (see `spl_autoload_register()`_).
  100. .. tip::
  101. The bundled extensions are great examples of how extensions work.
  102. Globals
  103. -------
  104. Global variables can be registered in an extension via the ``getGlobals()``
  105. method::
  106. class Project_Twig_Extension extends Twig_Extension
  107. {
  108. public function getGlobals()
  109. {
  110. return array(
  111. 'text' => new Text(),
  112. );
  113. }
  114. // ...
  115. }
  116. Functions
  117. ---------
  118. Functions can be registered in an extension via the ``getFunctions()``
  119. method::
  120. class Project_Twig_Extension extends Twig_Extension
  121. {
  122. public function getFunctions()
  123. {
  124. return array(
  125. 'lipsum' => new Twig_Function_Function('generate_lipsum'),
  126. );
  127. }
  128. // ...
  129. }
  130. Filters
  131. -------
  132. To add a filter to an extension, you need to override the ``getFilters()``
  133. method. This method must return an array of filters to add to the Twig
  134. environment::
  135. class Project_Twig_Extension extends Twig_Extension
  136. {
  137. public function getFilters()
  138. {
  139. return array(
  140. 'rot13' => new Twig_Filter_Function('str_rot13'),
  141. );
  142. }
  143. // ...
  144. }
  145. As you can see in the above code, the ``getFilters()`` method returns an array
  146. where keys are the name of the filters (``rot13``) and the values the
  147. definition of the filter (``new Twig_Filter_Function('str_rot13')``).
  148. As seen in the previous chapter, you can also define filters as static methods
  149. on the extension class::
  150. $twig->addFilter('rot13', new Twig_Filter_Function('Project_Twig_Extension::rot13Filter'));
  151. You can also use ``Twig_Filter_Method`` instead of ``Twig_Filter_Function``
  152. when defining a filter to use a method::
  153. class Project_Twig_Extension extends Twig_Extension
  154. {
  155. public function getFilters()
  156. {
  157. return array(
  158. 'rot13' => new Twig_Filter_Method($this, 'rot13Filter'),
  159. );
  160. }
  161. public function rot13Filter($string)
  162. {
  163. return str_rot13($string);
  164. }
  165. // ...
  166. }
  167. The first argument of the ``Twig_Filter_Method`` constructor is always
  168. ``$this``, the current extension object. The second one is the name of the
  169. method to call.
  170. Using methods for filters is a great way to package your filter without
  171. polluting the global namespace. This also gives the developer more flexibility
  172. at the cost of a small overhead.
  173. Overriding default Filters
  174. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  175. If some default core filters do not suit your needs, you can easily override
  176. them by creating your own core extension. Of course, you don't need to copy
  177. and paste the whole core extension code of Twig. Instead, you can just extends
  178. it and override the filter(s) you want by overriding the ``getFilters()``
  179. method::
  180. class MyCoreExtension extends Twig_Extension_Core
  181. {
  182. public function getFilters()
  183. {
  184. return array_merge(parent::getFilters(), array(
  185. 'date' => new Twig_Filter_Method($this, 'dateFilter'),
  186. // ...
  187. ));
  188. }
  189. public function dateFilter($timestamp, $format = 'F j, Y H:i')
  190. {
  191. return '...'.twig_date_format_filter($timestamp, $format);
  192. }
  193. // ...
  194. }
  195. Here, we override the ``date`` filter with a custom one. Using this new core
  196. extension is as simple as registering the ``MyCoreExtension`` extension by
  197. calling the ``addExtension()`` method on the environment instance::
  198. $twig = new Twig_Environment($loader);
  199. $twig->addExtension(new MyCoreExtension());
  200. But I can already hear some people wondering how it can work as the Core
  201. extension is loaded by default. That's true, but the trick is that both
  202. extensions share the same unique identifier (``core`` - defined in the
  203. ``getName()`` method). By registering an extension with the same name as an
  204. existing one, you have actually overridden the default one, even if it is
  205. already registered::
  206. $twig->addExtension(new Twig_Extension_Core());
  207. $twig->addExtension(new MyCoreExtension());
  208. Tags
  209. ----
  210. Adding a tag in an extension can be done by overriding the
  211. ``getTokenParsers()`` method. This method must return an array of tags to add
  212. to the Twig environment::
  213. class Project_Twig_Extension extends Twig_Extension
  214. {
  215. public function getTokenParsers()
  216. {
  217. return array(new Project_Set_TokenParser());
  218. }
  219. // ...
  220. }
  221. In the above code, we have added a single new tag, defined by the
  222. ``Project_Set_TokenParser`` class. The ``Project_Set_TokenParser`` class is
  223. responsible for parsing the tag and compiling it to PHP.
  224. Operators
  225. ---------
  226. The ``getOperators()`` methods allows to add new operators. Here is how to add
  227. ``!``, ``||``, and ``&&`` operators::
  228. class Project_Twig_Extension extends Twig_Extension
  229. {
  230. public function getOperators()
  231. {
  232. return array(
  233. array(
  234. '!' => array('precedence' => 50, 'class' => 'Twig_Node_Expression_Unary_Not'),
  235. ),
  236. array(
  237. '||' => array('precedence' => 10, 'class' => 'Twig_Node_Expression_Binary_Or', 'associativity' => Twig_ExpressionParser::OPERATOR_LEFT),
  238. '&&' => array('precedence' => 15, 'class' => 'Twig_Node_Expression_Binary_And', 'associativity' => Twig_ExpressionParser::OPERATOR_LEFT),
  239. ),
  240. );
  241. }
  242. // ...
  243. }
  244. Tests
  245. -----
  246. The ``getTests()`` methods allows to add new test functions::
  247. class Project_Twig_Extension extends Twig_Extension
  248. {
  249. public function getTests()
  250. {
  251. return array(
  252. 'even' => new Twig_Test_Function('twig_test_even'),
  253. );
  254. }
  255. // ...
  256. }
  257. .. _`spl_autoload_register()`: http://www.php.net/spl_autoload_register