api.rst 17KB

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