api.rst 16KB

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