api.rst 15KB

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