api.rst 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  1. Twig for Developers
  2. ===================
  3. This chapter describes the API to Twig and not the template language. It will
  4. be most useful as reference to those implementing the template interface to
  5. the application and not those who are creating Twig templates.
  6. Basics
  7. ------
  8. Twig uses a central object called the **environment** (of class
  9. ``Twig_Environment``). Instances of this class are used to store the
  10. configuration and extensions, and are used to load templates from the file
  11. system or other locations.
  12. Most applications will create one ``Twig_Environment`` object on application
  13. initialization and use that to load templates. In some cases it's however
  14. useful to have multiple environments side by side, if different configurations
  15. are in use.
  16. The simplest way to configure Twig to load templates for your application
  17. looks roughly like this::
  18. require_once '/path/to/lib/Twig/Autoloader.php';
  19. Twig_Autoloader::register();
  20. $loader = new Twig_Loader_Filesystem('/path/to/templates');
  21. $twig = new Twig_Environment($loader, array(
  22. 'cache' => '/path/to/compilation_cache',
  23. ));
  24. This will create a template environment with the default settings and a loader
  25. that looks up the templates in the ``/path/to/templates/`` folder. Different
  26. loaders are available and you can also write your own if you want to load
  27. templates from a database or other resources.
  28. .. note::
  29. Notice that the second argument of the environment is an array of options.
  30. The ``cache`` option is a compilation cache directory, where Twig caches
  31. the compiled templates to avoid the parsing phase for sub-sequent
  32. requests. It is very different from the cache you might want to add for
  33. the evaluated templates. For such a need, you can use any available PHP
  34. cache library.
  35. To load a template from this environment you just have to call the
  36. ``loadTemplate()`` method which then returns a ``Twig_Template`` instance::
  37. $template = $twig->loadTemplate('index.html');
  38. To render the template with some variables, call the ``render()`` method::
  39. echo $template->render(array('the' => 'variables', 'go' => 'here'));
  40. .. note::
  41. The ``display()`` method is a shortcut to output the template directly.
  42. Environment Options
  43. -------------------
  44. When creating a new ``Twig_Environment`` instance, you can pass an array of
  45. options as the constructor second argument::
  46. $twig = new Twig_Environment($loader, array('debug' => true));
  47. The following options are available:
  48. * ``debug``: When set to ``true``, the generated templates have a
  49. ``__toString()`` method that you can use to display the generated nodes
  50. (default to ``false``).
  51. * ``charset``: The charset used by the templates (default to ``utf-8``).
  52. * ``base_template_class``: The base template class to use for generated
  53. templates (default to ``Twig_Template``).
  54. * ``cache``: An absolute path where to store the compiled templates, or
  55. ``false`` to disable caching (which is the default).
  56. * ``auto_reload``: When developing with Twig, it's useful to recompile the
  57. template whenever the source code changes. If you don't provide a value for
  58. the ``auto_reload`` option, it will be determined automatically based on the
  59. ``debug`` value.
  60. * ``strict_variables``: If set to ``false``, Twig will silently ignore invalid
  61. variables (variables and or attributes/methods that do not exist) and
  62. replace them with a ``null`` value. When set to ``true``, Twig throws an
  63. exception instead (default to ``false``).
  64. * ``autoescape``: If set to ``true``, auto-escaping will be enabled by default
  65. for all templates (default to ``true``).
  66. * ``optimizations``: A flag that indicates which optimizations to apply
  67. (default to ``-1`` -- all optimizations are enabled; set it to ``0`` to
  68. disable).
  69. Loaders
  70. -------
  71. Loaders are responsible for loading templates from a resource such as the file
  72. system.
  73. Compilation Cache
  74. ~~~~~~~~~~~~~~~~~
  75. All template loaders can cache the compiled templates on the filesystem for
  76. future reuse. It speeds up Twig a lot as templates are only compiled once; and
  77. the performance boost is even larger if you use a PHP accelerator such as APC.
  78. See the ``cache`` and ``auto_reload`` options of ``Twig_Environment`` above
  79. for more information.
  80. Built-in Loaders
  81. ~~~~~~~~~~~~~~~~
  82. Here is a list of the built-in loaders Twig provides:
  83. * ``Twig_Loader_Filesystem``: Loads templates from the file system. This
  84. loader can find templates in folders on the file system and is the preferred
  85. way to load them::
  86. $loader = new Twig_Loader_Filesystem($templateDir);
  87. It can also look for templates in an array of directories::
  88. $loader = new Twig_Loader_Filesystem(array($templateDir1, $templateDir2));
  89. With such a configuration, Twig will first look for templates in
  90. ``$templateDir1`` and if they do not exist, it will fallback to look for
  91. them in the ``$templateDir2``.
  92. * ``Twig_Loader_String``: Loads templates from a string. It's a dummy loader
  93. as you pass it the source code directly::
  94. $loader = new Twig_Loader_String();
  95. * ``Twig_Loader_Array``: Loads a template from a PHP array. It's passed an
  96. array of strings bound to template names. This loader is useful for unit
  97. testing::
  98. $loader = new Twig_Loader_Array($templates);
  99. .. tip::
  100. When using the ``Array`` or ``String`` loaders with a cache mechanism, you
  101. should know that a new cache key is generated each time a template content
  102. "changes" (the cache key being the source code of the template). If you
  103. don't want to see your cache grows out of control, you need to take care
  104. of clearing the old cache file by yourself.
  105. Create your own Loader
  106. ~~~~~~~~~~~~~~~~~~~~~~
  107. All loaders implement the ``Twig_LoaderInterface``::
  108. interface Twig_LoaderInterface
  109. {
  110. /**
  111. * Gets the source code of a template, given its name.
  112. *
  113. * @param string $name string The name of the template to load
  114. *
  115. * @return string The template source code
  116. */
  117. function getSource($name);
  118. /**
  119. * Gets the cache key to use for the cache for a given template name.
  120. *
  121. * @param string $name string The name of the template to load
  122. *
  123. * @return string The cache key
  124. */
  125. function getCacheKey($name);
  126. /**
  127. * Returns true if the template is still fresh.
  128. *
  129. * @param string $name The template name
  130. * @param timestamp $time The last modification time of the cached template
  131. */
  132. function isFresh($name, $time);
  133. }
  134. As an example, here is how the built-in ``Twig_Loader_String`` reads::
  135. class Twig_Loader_String implements Twig_LoaderInterface
  136. {
  137. public function getSource($name)
  138. {
  139. return $name;
  140. }
  141. public function getCacheKey($name)
  142. {
  143. return $name;
  144. }
  145. public function isFresh($name, $time)
  146. {
  147. return false;
  148. }
  149. }
  150. The ``isFresh()`` method must return ``true`` if the current cached template
  151. is still fresh, given the last modification time, or ``false`` otherwise.
  152. Using Extensions
  153. ----------------
  154. Twig extensions are packages that add new features to Twig. Using an
  155. extension is as simple as using the ``addExtension()`` method::
  156. $twig->addExtension(new Twig_Extension_Sandbox());
  157. Twig comes bundled with the following extensions:
  158. * *Twig_Extension_Core*: Defines all the core features of Twig.
  159. * *Twig_Extension_Escaper*: Adds automatic output-escaping and the possibility
  160. to escape/unescape blocks of code.
  161. * *Twig_Extension_Sandbox*: Adds a sandbox mode to the default Twig
  162. environment, making it safe to evaluated untrusted code.
  163. * *Twig_Extension_Optimizer*: Optimizers the node tree before compilation.
  164. The core, escaper, and optimizer extensions do not need to be added to the
  165. Twig environment, as they are registered by default. You can disable an
  166. already registered extension::
  167. $twig->removeExtension('escaper');
  168. Built-in Extensions
  169. -------------------
  170. This section describes the features added by the built-in extensions.
  171. .. tip::
  172. Read the chapter about extending Twig to learn how to create your own
  173. extensions.
  174. Core Extension
  175. ~~~~~~~~~~~~~~
  176. The ``core`` extension defines all the core features of Twig:
  177. * Tags:
  178. * ``for``
  179. * ``if``
  180. * ``extends``
  181. * ``include``
  182. * ``block``
  183. * ``filter``
  184. * ``macro``
  185. * ``import``
  186. * ``from``
  187. * ``set``
  188. * ``spaceless``
  189. * Filters:
  190. * ``date``
  191. * ``format``
  192. * ``replace``
  193. * ``url_encode``
  194. * ``json_encode``
  195. * ``title``
  196. * ``capitalize``
  197. * ``upper``
  198. * ``lower``
  199. * ``striptags``
  200. * ``join``
  201. * ``reverse``
  202. * ``length``
  203. * ``sort``
  204. * ``merge``
  205. * ``default``
  206. * ``keys``
  207. * ``escape``
  208. * ``e``
  209. * Functions:
  210. * ``range``
  211. * ``constant``
  212. * ``cycle``
  213. * ``parent``
  214. * ``block``
  215. * Tests:
  216. * ``even``
  217. * ``odd``
  218. * ``defined``
  219. * ``sameas``
  220. * ``none``
  221. * ``divisibleby``
  222. * ``constant``
  223. * ``empty``
  224. Escaper Extension
  225. ~~~~~~~~~~~~~~~~~
  226. The ``escaper`` extension adds automatic output escaping to Twig. It defines a
  227. new tag, ``autoescape``, and a new filter, ``raw``.
  228. When creating the escaper extension, you can switch on or off the global
  229. output escaping strategy::
  230. $escaper = new Twig_Extension_Escaper(true);
  231. $twig->addExtension($escaper);
  232. If set to ``true``, all variables in templates are escaped, except those using
  233. the ``raw`` filter:
  234. .. code-block:: jinja
  235. {{ article.to_html|raw }}
  236. You can also change the escaping mode locally by using the ``autoescape`` tag:
  237. .. code-block:: jinja
  238. {% autoescape true %}
  239. {% var %}
  240. {% var|raw %} {# var won't be escaped #}
  241. {% var|escape %} {# var won't be doubled-escaped #}
  242. {% endautoescape %}
  243. .. warning::
  244. The ``autoescape`` tag has no effect on included files.
  245. The escaping rules are implemented as follows:
  246. * Literals (integers, booleans, arrays, ...) used in the template directly as
  247. variables or filter arguments are never automatically escaped:
  248. .. code-block:: jinja
  249. {{ "Twig<br />" }} {# won't be escaped #}
  250. {% set text = "Twig<br />" %}
  251. {{ text }} {# will be escaped #}
  252. * Expressions which the result is always a literal or a variable marked safe
  253. are never automatically escaped:
  254. .. code-block:: jinja
  255. {{ foo ? "Twig<br />" : "<br />Twig" }} {# won't be escaped #}
  256. {% set text = "Twig<br />" %}
  257. {{ foo ? text : "<br />Twig" }} {# will be escaped #}
  258. {% set text = "Twig<br />" %}
  259. {{ foo ? text|raw : "<br />Twig" }} {# won't be escaped #}
  260. {% set text = "Twig<br />" %}
  261. {{ foo ? text|escape : "<br />Twig" }} {# the result of the expression won't be escaped #}
  262. * Escaping is applied before printing, after any other filter is applied:
  263. .. code-block:: jinja
  264. {{ var|upper }} {# is equivalent to {{ var|upper|escape }} #}
  265. * The `raw` filter should only be used at the end of the filter chain:
  266. .. code-block:: jinja
  267. {{ var|raw|upper }} {# will be escaped #}
  268. {{ var|upper|raw }} {# won't be escaped #}
  269. * Automatic escaping is not applied if the last filter in the chain is marked
  270. safe for the current context (e.g. ``html`` or ``js``). ``escaper`` and
  271. ``escaper('html')`` are marked safe for html, ``escaper('js')`` is marked
  272. safe for javascript, ``raw`` is marked safe for everything.
  273. .. code-block:: jinja
  274. {% autoescape true js %}
  275. {{ var|escape('html') }} {# will be escaped for html and javascript #}
  276. {{ var }} {# will be escaped for javascript #}
  277. {{ var|escape('js') }} {# won't be double-escaped #}
  278. {% endautoescape %}
  279. .. note::
  280. Note that autoescaping has some limitations as escaping is applied on
  281. expressions after evaluation. For instance, when working with
  282. concatenation, ``{{ foo|raw ~ bar }}`` won't give the expected result as
  283. escaping is applied on the result of the concatenation, not on the
  284. individual variables (so, the ``raw`` filter won't have any effect here).
  285. Sandbox Extension
  286. ~~~~~~~~~~~~~~~~~
  287. The ``sandbox`` extension can be used to evaluate untrusted code. Access to
  288. unsafe attributes and methods is prohibited. The sandbox security is managed
  289. by a policy instance. By default, Twig comes with one policy class:
  290. ``Twig_Sandbox_SecurityPolicy``. This class allows you to white-list some
  291. tags, filters, properties, and methods::
  292. $tags = array('if');
  293. $filters = array('upper');
  294. $methods = array(
  295. 'Article' => array('getTitle', 'getBody'),
  296. );
  297. $properties = array(
  298. 'Article' => array('title', 'body'),
  299. );
  300. $functions = array('range');
  301. $policy = new Twig_Sandbox_SecurityPolicy($tags, $filters, $methods, $properties, $functions);
  302. With the previous configuration, the security policy will only allow usage of
  303. the ``if`` tag, and the ``upper`` filter. Moreover, the templates will only be
  304. able to call the ``getTitle()`` and ``getBody()`` methods on ``Article``
  305. objects, and the ``title`` and ``body`` public properties. Everything else
  306. won't be allowed and will generate a ``Twig_Sandbox_SecurityError`` exception.
  307. The policy object is the first argument of the sandbox constructor::
  308. $sandbox = new Twig_Extension_Sandbox($policy);
  309. $twig->addExtension($sandbox);
  310. By default, the sandbox mode is disabled and should be enabled when including
  311. untrusted template code by using the ``sandbox`` tag:
  312. .. code-block:: jinja
  313. {% sandbox %}
  314. {% include 'user.html' %}
  315. {% endsandbox %}
  316. You can sandbox all templates by passing ``true`` as the second argument of
  317. the extension constructor::
  318. $sandbox = new Twig_Extension_Sandbox($policy, true);
  319. Optimizer Extension
  320. ~~~~~~~~~~~~~~~~~~~
  321. The ``optimizer`` extension optimizes the node tree before compilation::
  322. $twig->addExtension(new Twig_Extension_Optimizer());
  323. By default, all optimizations are turned on. You can select the ones you want
  324. to enable by passing them to the constructor::
  325. $optimizer = new Twig_Extension_Optimizer(Twig_NodeVisitor_Optimizer::OPTIMIZE_FOR);
  326. $twig->addExtension($optimizer);
  327. Exceptions
  328. ----------
  329. Twig can throw exceptions:
  330. * ``Twig_Error``: The base exception for all errors.
  331. * ``Twig_Error_Syntax``: Thrown to tell the user that there is a problem with
  332. the template syntax.
  333. * ``Twig_Error_Runtime``: Thrown when an error occurs at runtime (when a filter
  334. does not exist for instance).
  335. * ``Twig_Error_Loader``: Thrown when an error occurs during template loading.
  336. * ``Twig_Sandbox_SecurityError``: Thrown when an unallowed tag, filter, or
  337. method is called in a sandboxed template.