/usr/share/doc/php-twig/manual/api.html is in php-twig-doc 2.4.6-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 | <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Twig for Developers — php-twig-doc 2.4.6 documentation</title>
<link rel="stylesheet" href="_static/classic.css" type="text/css" />
<link rel="stylesheet" href="_static/pygments.css" type="text/css" />
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT: './',
VERSION: '2.4.6',
COLLAPSE_INDEX: false,
FILE_SUFFIX: '.html',
HAS_SOURCE: true,
SOURCELINK_SUFFIX: '.txt'
};
</script>
<script type="text/javascript" src="_static/jquery.js"></script>
<script type="text/javascript" src="_static/underscore.js"></script>
<script type="text/javascript" src="_static/doctools.js"></script>
<link rel="index" title="Index" href="genindex.html" />
<link rel="search" title="Search" href="search.html" />
<link rel="next" title="Extending Twig" href="advanced.html" />
<link rel="prev" title="Twig for Template Designers" href="templates.html" />
</head>
<body>
<div class="related" role="navigation" aria-label="related navigation">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="genindex.html" title="General Index"
accesskey="I">index</a></li>
<li class="right" >
<a href="advanced.html" title="Extending Twig"
accesskey="N">next</a> |</li>
<li class="right" >
<a href="templates.html" title="Twig for Template Designers"
accesskey="P">previous</a> |</li>
<li class="nav-item nav-item-0"><a href="index.html">php-twig-doc 2.4.6 documentation</a> »</li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<div class="section" id="twig-for-developers">
<h1>Twig for Developers<a class="headerlink" href="#twig-for-developers" title="Permalink to this headline">¶</a></h1>
<p>This chapter describes the API to Twig and not the template language. It will
be most useful as reference to those implementing the template interface to
the application and not those who are creating Twig templates.</p>
<div class="section" id="basics">
<h2>Basics<a class="headerlink" href="#basics" title="Permalink to this headline">¶</a></h2>
<p>Twig uses a central object called the <strong>environment</strong> (of class
<code class="docutils literal"><span class="pre">Twig_Environment</span></code>). Instances of this class are used to store the
configuration and extensions, and are used to load templates from the file
system or other locations.</p>
<p>Most applications will create one <code class="docutils literal"><span class="pre">Twig_Environment</span></code> object on application
initialization and use that to load templates. In some cases it’s however
useful to have multiple environments side by side, if different configurations
are in use.</p>
<p>The simplest way to configure Twig to load templates for your application
looks roughly like this:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>require_once '/path/to/vendor/autoload.php';
$loader = new Twig_Loader_Filesystem('/path/to/templates');
$twig = new Twig_Environment($loader, array(
'cache' => '/path/to/compilation_cache',
));
</pre></div>
</div>
<p>This will create a template environment with the default settings and a loader
that looks up the templates in the <code class="docutils literal"><span class="pre">/path/to/templates/</span></code> folder. Different
loaders are available and you can also write your own if you want to load
templates from a database or other resources.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Notice that the second argument of the environment is an array of options.
The <code class="docutils literal"><span class="pre">cache</span></code> option is a compilation cache directory, where Twig caches
the compiled templates to avoid the parsing phase for sub-sequent
requests. It is very different from the cache you might want to add for
the evaluated templates. For such a need, you can use any available PHP
cache library.</p>
</div>
</div>
<div class="section" id="rendering-templates">
<h2>Rendering Templates<a class="headerlink" href="#rendering-templates" title="Permalink to this headline">¶</a></h2>
<p>To load a template from a Twig environment, call the <code class="docutils literal"><span class="pre">load()</span></code> method which
returns a <code class="docutils literal"><span class="pre">Twig_TemplateWrapper</span></code> instance:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>$template = $twig->load('index.html');
</pre></div>
</div>
<p>To render the template with some variables, call the <code class="docutils literal"><span class="pre">render()</span></code> method:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>echo $template->render(array('the' => 'variables', 'go' => 'here'));
</pre></div>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The <code class="docutils literal"><span class="pre">display()</span></code> method is a shortcut to output the template directly.</p>
</div>
<p>You can also load and render the template in one fell swoop:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>echo $twig->render('index.html', array('the' => 'variables', 'go' => 'here'));
</pre></div>
</div>
<p>If a template defines blocks, they can be rendered individually via the
<code class="docutils literal"><span class="pre">renderBlock()</span></code> call:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>echo $template->renderBlock('block_name', array('the' => 'variables', 'go' => 'here'));
</pre></div>
</div>
</div>
<div class="section" id="environment-options">
<span id="id1"></span><h2>Environment Options<a class="headerlink" href="#environment-options" title="Permalink to this headline">¶</a></h2>
<p>When creating a new <code class="docutils literal"><span class="pre">Twig_Environment</span></code> instance, you can pass an array of
options as the constructor second argument:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>$twig = new Twig_Environment($loader, array('debug' => true));
</pre></div>
</div>
<p>The following options are available:</p>
<ul>
<li><p class="first"><code class="docutils literal"><span class="pre">debug</span></code> <em>boolean</em></p>
<p>When set to <code class="docutils literal"><span class="pre">true</span></code>, the generated templates have a
<code class="docutils literal"><span class="pre">__toString()</span></code> method that you can use to display the generated nodes
(default to <code class="docutils literal"><span class="pre">false</span></code>).</p>
</li>
<li><p class="first"><code class="docutils literal"><span class="pre">charset</span></code> <em>string</em> (defaults to <code class="docutils literal"><span class="pre">utf-8</span></code>)</p>
<p>The charset used by the templates.</p>
</li>
<li><p class="first"><code class="docutils literal"><span class="pre">base_template_class</span></code> <em>string</em> (defaults to <code class="docutils literal"><span class="pre">Twig_Template</span></code>)</p>
<p>The base template class to use for generated
templates.</p>
</li>
<li><p class="first"><code class="docutils literal"><span class="pre">cache</span></code> <em>string</em> or <code class="docutils literal"><span class="pre">false</span></code></p>
<p>An absolute path where to store the compiled templates, or
<code class="docutils literal"><span class="pre">false</span></code> to disable caching (which is the default).</p>
</li>
<li><p class="first"><code class="docutils literal"><span class="pre">auto_reload</span></code> <em>boolean</em></p>
<p>When developing with Twig, it’s useful to recompile the
template whenever the source code changes. If you don’t provide a value for
the <code class="docutils literal"><span class="pre">auto_reload</span></code> option, it will be determined automatically based on the
<code class="docutils literal"><span class="pre">debug</span></code> value.</p>
</li>
<li><p class="first"><code class="docutils literal"><span class="pre">strict_variables</span></code> <em>boolean</em></p>
<p>If set to <code class="docutils literal"><span class="pre">false</span></code>, Twig will silently ignore invalid
variables (variables and or attributes/methods that do not exist) and
replace them with a <code class="docutils literal"><span class="pre">null</span></code> value. When set to <code class="docutils literal"><span class="pre">true</span></code>, Twig throws an
exception instead (default to <code class="docutils literal"><span class="pre">false</span></code>).</p>
</li>
<li><p class="first"><code class="docutils literal"><span class="pre">autoescape</span></code> <em>string</em></p>
<p>Sets the default auto-escaping strategy (<code class="docutils literal"><span class="pre">name</span></code>, <code class="docutils literal"><span class="pre">html</span></code>, <code class="docutils literal"><span class="pre">js</span></code>, <code class="docutils literal"><span class="pre">css</span></code>,
<code class="docutils literal"><span class="pre">url</span></code>, <code class="docutils literal"><span class="pre">html_attr</span></code>, or a PHP callback that takes the template “filename”
and returns the escaping strategy to use – the callback cannot be a function
name to avoid collision with built-in escaping strategies); set it to
<code class="docutils literal"><span class="pre">false</span></code> to disable auto-escaping. The <code class="docutils literal"><span class="pre">name</span></code> escaping strategy determines
the escaping strategy to use for a template based on the template filename
extension (this strategy does not incur any overhead at runtime as
auto-escaping is done at compilation time.)</p>
</li>
<li><p class="first"><code class="docutils literal"><span class="pre">optimizations</span></code> <em>integer</em></p>
<p>A flag that indicates which optimizations to apply
(default to <code class="docutils literal"><span class="pre">-1</span></code> – all optimizations are enabled; set it to <code class="docutils literal"><span class="pre">0</span></code> to
disable).</p>
</li>
</ul>
</div>
<div class="section" id="loaders">
<h2>Loaders<a class="headerlink" href="#loaders" title="Permalink to this headline">¶</a></h2>
<p>Loaders are responsible for loading templates from a resource such as the file
system.</p>
<div class="section" id="compilation-cache">
<h3>Compilation Cache<a class="headerlink" href="#compilation-cache" title="Permalink to this headline">¶</a></h3>
<p>All template loaders can cache the compiled templates on the filesystem for
future reuse. It speeds up Twig a lot as templates are only compiled once; and
the performance boost is even larger if you use a PHP accelerator such as APC.
See the <code class="docutils literal"><span class="pre">cache</span></code> and <code class="docutils literal"><span class="pre">auto_reload</span></code> options of <code class="docutils literal"><span class="pre">Twig_Environment</span></code> above
for more information.</p>
</div>
<div class="section" id="built-in-loaders">
<h3>Built-in Loaders<a class="headerlink" href="#built-in-loaders" title="Permalink to this headline">¶</a></h3>
<p>Here is a list of the built-in loaders Twig provides:</p>
<div class="section" id="twig-loader-filesystem">
<h4><code class="docutils literal"><span class="pre">Twig_Loader_Filesystem</span></code><a class="headerlink" href="#twig-loader-filesystem" title="Permalink to this headline">¶</a></h4>
<p><code class="docutils literal"><span class="pre">Twig_Loader_Filesystem</span></code> loads templates from the file system. This loader
can find templates in folders on the file system and is the preferred way to
load them:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>$loader = new Twig_Loader_Filesystem($templateDir);
</pre></div>
</div>
<p>It can also look for templates in an array of directories:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>$loader = new Twig_Loader_Filesystem(array($templateDir1, $templateDir2));
</pre></div>
</div>
<p>With such a configuration, Twig will first look for templates in
<code class="docutils literal"><span class="pre">$templateDir1</span></code> and if they do not exist, it will fallback to look for them
in the <code class="docutils literal"><span class="pre">$templateDir2</span></code>.</p>
<p>You can add or prepend paths via the <code class="docutils literal"><span class="pre">addPath()</span></code> and <code class="docutils literal"><span class="pre">prependPath()</span></code>
methods:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>$loader->addPath($templateDir3);
$loader->prependPath($templateDir4);
</pre></div>
</div>
<p>The filesystem loader also supports namespaced templates. This allows to group
your templates under different namespaces which have their own template paths.</p>
<p>When using the <code class="docutils literal"><span class="pre">setPaths()</span></code>, <code class="docutils literal"><span class="pre">addPath()</span></code>, and <code class="docutils literal"><span class="pre">prependPath()</span></code> methods,
specify the namespace as the second argument (when not specified, these
methods act on the “main” namespace):</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>$loader->addPath($templateDir, 'admin');
</pre></div>
</div>
<p>Namespaced templates can be accessed via the special
<code class="docutils literal"><span class="pre">@namespace_name/template_path</span></code> notation:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>$twig->render('@admin/index.html', array());
</pre></div>
</div>
<p><code class="docutils literal"><span class="pre">Twig_Loader_Filesystem</span></code> support absolute and relative paths. Using relative
paths is preferred as it makes the cache keys independent of the project root
directory (for instance, it allows warming the cache from a build server where
the directory might be different from the one used on production servers):</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>$loader = new Twig_Loader_Filesystem('templates', getcwd().'/..');
</pre></div>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">When not passing the root path as a second argument, Twig uses <code class="docutils literal"><span class="pre">getcwd()</span></code>
for relative paths.</p>
</div>
</div>
<div class="section" id="twig-loader-array">
<h4><code class="docutils literal"><span class="pre">Twig_Loader_Array</span></code><a class="headerlink" href="#twig-loader-array" title="Permalink to this headline">¶</a></h4>
<p><code class="docutils literal"><span class="pre">Twig_Loader_Array</span></code> loads a template from a PHP array. It’s passed an array
of strings bound to template names:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>$loader = new Twig_Loader_Array(array(
'index.html' => 'Hello {{ name }}!',
));
$twig = new Twig_Environment($loader);
echo $twig->render('index.html', array('name' => 'Fabien'));
</pre></div>
</div>
<p>This loader is very useful for unit testing. It can also be used for small
projects where storing all templates in a single PHP file might make sense.</p>
<div class="admonition tip">
<p class="first admonition-title">Tip</p>
<p class="last">When using the <code class="docutils literal"><span class="pre">Array</span></code> loader with a cache mechanism, you
should know that a new cache key is generated each time a template content
“changes” (the cache key being the source code of the template). If you
don’t want to see your cache grows out of control, you need to take care
of clearing the old cache file by yourself.</p>
</div>
</div>
<div class="section" id="twig-loader-chain">
<h4><code class="docutils literal"><span class="pre">Twig_Loader_Chain</span></code><a class="headerlink" href="#twig-loader-chain" title="Permalink to this headline">¶</a></h4>
<p><code class="docutils literal"><span class="pre">Twig_Loader_Chain</span></code> delegates the loading of templates to other loaders:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>$loader1 = new Twig_Loader_Array(array(
'base.html' => '{% block content %}{% endblock %}',
));
$loader2 = new Twig_Loader_Array(array(
'index.html' => '{% extends "base.html" %}{% block content %}Hello {{ name }}{% endblock %}',
'base.html' => 'Will never be loaded',
));
$loader = new Twig_Loader_Chain(array($loader1, $loader2));
$twig = new Twig_Environment($loader);
</pre></div>
</div>
<p>When looking for a template, Twig will try each loader in turn and it will
return as soon as the template is found. When rendering the <code class="docutils literal"><span class="pre">index.html</span></code>
template from the above example, Twig will load it with <code class="docutils literal"><span class="pre">$loader2</span></code> but the
<code class="docutils literal"><span class="pre">base.html</span></code> template will be loaded from <code class="docutils literal"><span class="pre">$loader1</span></code>.</p>
<p><code class="docutils literal"><span class="pre">Twig_Loader_Chain</span></code> accepts any loader that implements
<code class="docutils literal"><span class="pre">Twig_LoaderInterface</span></code>.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">You can also add loaders via the <code class="docutils literal"><span class="pre">addLoader()</span></code> method.</p>
</div>
</div>
</div>
<div class="section" id="create-your-own-loader">
<h3>Create your own Loader<a class="headerlink" href="#create-your-own-loader" title="Permalink to this headline">¶</a></h3>
<p>All loaders implement the <code class="docutils literal"><span class="pre">Twig_LoaderInterface</span></code>:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>interface Twig_LoaderInterface
{
/**
* Returns the source context for a given template logical name.
*
* @param string $name The template logical name
*
* @return Twig_Source
*
* @throws Twig_Error_Loader When $name is not found
*/
public function getSourceContext($name);
/**
* Gets the cache key to use for the cache for a given template name.
*
* @param string $name The name of the template to load
*
* @return string The cache key
*
* @throws Twig_Error_Loader When $name is not found
*/
public function getCacheKey($name);
/**
* Returns true if the template is still fresh.
*
* @param string $name The template name
* @param timestamp $time The last modification time of the cached template
*
* @return bool true if the template is fresh, false otherwise
*
* @throws Twig_Error_Loader When $name is not found
*/
public function isFresh($name, $time);
/**
* Check if we have the source code of a template, given its name.
*
* @param string $name The name of the template to check if we can load
*
* @return bool If the template source code is handled by this loader or not
*/
public function exists($name);
}
</pre></div>
</div>
<p>The <code class="docutils literal"><span class="pre">isFresh()</span></code> method must return <code class="docutils literal"><span class="pre">true</span></code> if the current cached template
is still fresh, given the last modification time, or <code class="docutils literal"><span class="pre">false</span></code> otherwise.</p>
<p>The <code class="docutils literal"><span class="pre">getSourceContext()</span></code> method must return an instance of <code class="docutils literal"><span class="pre">Twig_Source</span></code>.</p>
</div>
</div>
<div class="section" id="using-extensions">
<h2>Using Extensions<a class="headerlink" href="#using-extensions" title="Permalink to this headline">¶</a></h2>
<p>Twig extensions are packages that add new features to Twig. Using an
extension is as simple as using the <code class="docutils literal"><span class="pre">addExtension()</span></code> method:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>$twig->addExtension(new Twig_Extension_Sandbox());
</pre></div>
</div>
<p>Twig comes bundled with the following extensions:</p>
<ul class="simple">
<li><em>Twig_Extension_Core</em>: Defines all the core features of Twig.</li>
<li><em>Twig_Extension_Escaper</em>: Adds automatic output-escaping and the possibility
to escape/unescape blocks of code.</li>
<li><em>Twig_Extension_Sandbox</em>: Adds a sandbox mode to the default Twig
environment, making it safe to evaluate untrusted code.</li>
<li><em>Twig_Extension_Profiler</em>: Enabled the built-in Twig profiler.</li>
<li><em>Twig_Extension_Optimizer</em>: Optimizes the node tree before compilation.</li>
</ul>
<p>The core, escaper, and optimizer extensions do not need to be added to the
Twig environment, as they are registered by default.</p>
</div>
<div class="section" id="built-in-extensions">
<h2>Built-in Extensions<a class="headerlink" href="#built-in-extensions" title="Permalink to this headline">¶</a></h2>
<p>This section describes the features added by the built-in extensions.</p>
<div class="admonition tip">
<p class="first admonition-title">Tip</p>
<p class="last">Read the chapter about extending Twig to learn how to create your own
extensions.</p>
</div>
<div class="section" id="core-extension">
<h3>Core Extension<a class="headerlink" href="#core-extension" title="Permalink to this headline">¶</a></h3>
<p>The <code class="docutils literal"><span class="pre">core</span></code> extension defines all the core features of Twig:</p>
<ul class="simple">
<li><a class="reference internal" href="tags/index.html"><span class="doc">Tags</span></a>;</li>
<li><a class="reference internal" href="filters/index.html"><span class="doc">Filters</span></a>;</li>
<li><a class="reference internal" href="functions/index.html"><span class="doc">Functions</span></a>;</li>
<li><a class="reference internal" href="tests/index.html"><span class="doc">Tests</span></a>.</li>
</ul>
</div>
<div class="section" id="escaper-extension">
<h3>Escaper Extension<a class="headerlink" href="#escaper-extension" title="Permalink to this headline">¶</a></h3>
<p>The <code class="docutils literal"><span class="pre">escaper</span></code> extension adds automatic output escaping to Twig. It defines a
tag, <code class="docutils literal"><span class="pre">autoescape</span></code>, and a filter, <code class="docutils literal"><span class="pre">raw</span></code>.</p>
<p>When creating the escaper extension, you can switch on or off the global
output escaping strategy:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>$escaper = new Twig_Extension_Escaper('html');
$twig->addExtension($escaper);
</pre></div>
</div>
<p>If set to <code class="docutils literal"><span class="pre">html</span></code>, all variables in templates are escaped (using the <code class="docutils literal"><span class="pre">html</span></code>
escaping strategy), except those using the <code class="docutils literal"><span class="pre">raw</span></code> filter:</p>
<div class="highlight-jinja"><div class="highlight"><pre><span></span><span class="cp">{{</span> <span class="nv">article.to_html</span><span class="o">|</span><span class="nf">raw</span> <span class="cp">}}</span><span class="x"></span>
</pre></div>
</div>
<p>You can also change the escaping mode locally by using the <code class="docutils literal"><span class="pre">autoescape</span></code> tag:</p>
<div class="highlight-jinja"><div class="highlight"><pre><span></span><span class="cp">{%</span> <span class="k">autoescape</span> <span class="s1">'html'</span> <span class="cp">%}</span><span class="x"></span>
<span class="x"> </span><span class="cp">{{</span> <span class="nv">var</span> <span class="cp">}}</span><span class="x"></span>
<span class="x"> </span><span class="cp">{{</span> <span class="nv">var</span><span class="o">|</span><span class="nf">raw</span> <span class="cp">}}</span><span class="x"> </span><span class="c">{# var won't be escaped #}</span><span class="x"></span>
<span class="x"> </span><span class="cp">{{</span> <span class="nv">var</span><span class="o">|</span><span class="nf">escape</span> <span class="cp">}}</span><span class="x"> </span><span class="c">{# var won't be double-escaped #}</span><span class="x"></span>
<span class="cp">{%</span> <span class="k">endautoescape</span> <span class="cp">%}</span><span class="x"></span>
</pre></div>
</div>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">The <code class="docutils literal"><span class="pre">autoescape</span></code> tag has no effect on included files.</p>
</div>
<p>The escaping rules are implemented as follows:</p>
<ul>
<li><p class="first">Literals (integers, booleans, arrays, …) used in the template directly as
variables or filter arguments are never automatically escaped:</p>
<div class="highlight-jinja"><div class="highlight"><pre><span></span><span class="cp">{{</span> <span class="s2">"Twig<br />"</span> <span class="cp">}}</span><span class="x"> </span><span class="c">{# won't be escaped #}</span><span class="x"></span>
<span class="cp">{%</span> <span class="k">set</span> <span class="nv">text</span> <span class="o">=</span> <span class="s2">"Twig<br />"</span> <span class="cp">%}</span><span class="x"></span>
<span class="cp">{{</span> <span class="nv">text</span> <span class="cp">}}</span><span class="x"> </span><span class="c">{# will be escaped #}</span><span class="x"></span>
</pre></div>
</div>
</li>
<li><p class="first">Expressions which the result is always a literal or a variable marked safe
are never automatically escaped:</p>
<div class="highlight-jinja"><div class="highlight"><pre><span></span>{{ foo ? "Twig<br />" : "<br />Twig" }} {# won't be escaped #}
{% set text = "Twig<br />" %}
{{ foo ? text : "<br />Twig" }} {# will be escaped #}
{% set text = "Twig<br />" %}
{{ foo ? text|raw : "<br />Twig" }} {# won't be escaped #}
{% set text = "Twig<br />" %}
{{ foo ? text|escape : "<br />Twig" }} {# the result of the expression won't be escaped #}
</pre></div>
</div>
</li>
<li><p class="first">Escaping is applied before printing, after any other filter is applied:</p>
<div class="highlight-jinja"><div class="highlight"><pre><span></span><span class="cp">{{</span> <span class="nv">var</span><span class="o">|</span><span class="nf">upper</span> <span class="cp">}}</span><span class="x"> </span><span class="c">{# is equivalent to {{ var|upper|escape }} #}</span><span class="x"></span>
</pre></div>
</div>
</li>
<li><p class="first">The <cite>raw</cite> filter should only be used at the end of the filter chain:</p>
<div class="highlight-jinja"><div class="highlight"><pre><span></span><span class="cp">{{</span> <span class="nv">var</span><span class="o">|</span><span class="nf">raw</span><span class="o">|</span><span class="nf">upper</span> <span class="cp">}}</span><span class="x"> </span><span class="c">{# will be escaped #}</span><span class="x"></span>
<span class="cp">{{</span> <span class="nv">var</span><span class="o">|</span><span class="nf">upper</span><span class="o">|</span><span class="nf">raw</span> <span class="cp">}}</span><span class="x"> </span><span class="c">{# won't be escaped #}</span><span class="x"></span>
</pre></div>
</div>
</li>
<li><p class="first">Automatic escaping is not applied if the last filter in the chain is marked
safe for the current context (e.g. <code class="docutils literal"><span class="pre">html</span></code> or <code class="docutils literal"><span class="pre">js</span></code>). <code class="docutils literal"><span class="pre">escape</span></code> and
<code class="docutils literal"><span class="pre">escape('html')</span></code> are marked safe for HTML, <code class="docutils literal"><span class="pre">escape('js')</span></code> is marked
safe for JavaScript, <code class="docutils literal"><span class="pre">raw</span></code> is marked safe for everything.</p>
<div class="highlight-jinja"><div class="highlight"><pre><span></span><span class="cp">{%</span> <span class="k">autoescape</span> <span class="s1">'js'</span> <span class="cp">%}</span><span class="x"></span>
<span class="x"> </span><span class="cp">{{</span> <span class="nv">var</span><span class="o">|</span><span class="nf">escape</span><span class="o">(</span><span class="s1">'html'</span><span class="o">)</span> <span class="cp">}}</span><span class="x"> </span><span class="c">{# will be escaped for HTML and JavaScript #}</span><span class="x"></span>
<span class="x"> </span><span class="cp">{{</span> <span class="nv">var</span> <span class="cp">}}</span><span class="x"> </span><span class="c">{# will be escaped for JavaScript #}</span><span class="x"></span>
<span class="x"> </span><span class="cp">{{</span> <span class="nv">var</span><span class="o">|</span><span class="nf">escape</span><span class="o">(</span><span class="s1">'js'</span><span class="o">)</span> <span class="cp">}}</span><span class="x"> </span><span class="c">{# won't be double-escaped #}</span><span class="x"></span>
<span class="cp">{%</span> <span class="k">endautoescape</span> <span class="cp">%}</span><span class="x"></span>
</pre></div>
</div>
</li>
</ul>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Note that autoescaping has some limitations as escaping is applied on
expressions after evaluation. For instance, when working with
concatenation, <code class="docutils literal"><span class="pre">{{</span> <span class="pre">foo|raw</span> <span class="pre">~</span> <span class="pre">bar</span> <span class="pre">}}</span></code> won’t give the expected result as
escaping is applied on the result of the concatenation, not on the
individual variables (so, the <code class="docutils literal"><span class="pre">raw</span></code> filter won’t have any effect here).</p>
</div>
</div>
<div class="section" id="sandbox-extension">
<h3>Sandbox Extension<a class="headerlink" href="#sandbox-extension" title="Permalink to this headline">¶</a></h3>
<p>The <code class="docutils literal"><span class="pre">sandbox</span></code> extension can be used to evaluate untrusted code. Access to
unsafe attributes and methods is prohibited. The sandbox security is managed
by a policy instance. By default, Twig comes with one policy class:
<code class="docutils literal"><span class="pre">Twig_Sandbox_SecurityPolicy</span></code>. This class allows you to white-list some
tags, filters, properties, and methods:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>$tags = array('if');
$filters = array('upper');
$methods = array(
'Article' => array('getTitle', 'getBody'),
);
$properties = array(
'Article' => array('title', 'body'),
);
$functions = array('range');
$policy = new Twig_Sandbox_SecurityPolicy($tags, $filters, $methods, $properties, $functions);
</pre></div>
</div>
<p>With the previous configuration, the security policy will only allow usage of
the <code class="docutils literal"><span class="pre">if</span></code> tag, and the <code class="docutils literal"><span class="pre">upper</span></code> filter. Moreover, the templates will only be
able to call the <code class="docutils literal"><span class="pre">getTitle()</span></code> and <code class="docutils literal"><span class="pre">getBody()</span></code> methods on <code class="docutils literal"><span class="pre">Article</span></code>
objects, and the <code class="docutils literal"><span class="pre">title</span></code> and <code class="docutils literal"><span class="pre">body</span></code> public properties. Everything else
won’t be allowed and will generate a <code class="docutils literal"><span class="pre">Twig_Sandbox_SecurityError</span></code> exception.</p>
<p>The policy object is the first argument of the sandbox constructor:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>$sandbox = new Twig_Extension_Sandbox($policy);
$twig->addExtension($sandbox);
</pre></div>
</div>
<p>By default, the sandbox mode is disabled and should be enabled when including
untrusted template code by using the <code class="docutils literal"><span class="pre">sandbox</span></code> tag:</p>
<div class="highlight-jinja"><div class="highlight"><pre><span></span><span class="cp">{%</span> <span class="k">sandbox</span> <span class="cp">%}</span><span class="x"></span>
<span class="x"> </span><span class="cp">{%</span> <span class="k">include</span> <span class="s1">'user.html'</span> <span class="cp">%}</span><span class="x"></span>
<span class="cp">{%</span> <span class="k">endsandbox</span> <span class="cp">%}</span><span class="x"></span>
</pre></div>
</div>
<p>You can sandbox all templates by passing <code class="docutils literal"><span class="pre">true</span></code> as the second argument of
the extension constructor:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>$sandbox = new Twig_Extension_Sandbox($policy, true);
</pre></div>
</div>
</div>
<div class="section" id="profiler-extension">
<h3>Profiler Extension<a class="headerlink" href="#profiler-extension" title="Permalink to this headline">¶</a></h3>
<p>The <code class="docutils literal"><span class="pre">profiler</span></code> extension enables a profiler for Twig templates; it should
only be used on your development machines as it adds some overhead:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>$profile = new Twig_Profiler_Profile();
$twig->addExtension(new Twig_Extension_Profiler($profile));
$dumper = new Twig_Profiler_Dumper_Text();
echo $dumper->dump($profile);
</pre></div>
</div>
<p>A profile contains information about time and memory consumption for template,
block, and macro executions.</p>
<p>You can also dump the data in a <a class="reference external" href="https://blackfire.io/">Blackfire.io</a>
compatible format:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>$dumper = new Twig_Profiler_Dumper_Blackfire();
file_put_contents('/path/to/profile.prof', $dumper->dump($profile));
</pre></div>
</div>
<p>Upload the profile to visualize it (create a <a class="reference external" href="https://blackfire.io/signup">free account</a> first):</p>
<div class="highlight-sh"><div class="highlight"><pre><span></span>blackfire --slot<span class="o">=</span><span class="m">7</span> upload /path/to/profile.prof
</pre></div>
</div>
</div>
<div class="section" id="optimizer-extension">
<h3>Optimizer Extension<a class="headerlink" href="#optimizer-extension" title="Permalink to this headline">¶</a></h3>
<p>The <code class="docutils literal"><span class="pre">optimizer</span></code> extension optimizes the node tree before compilation:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>$twig->addExtension(new Twig_Extension_Optimizer());
</pre></div>
</div>
<p>By default, all optimizations are turned on. You can select the ones you want
to enable by passing them to the constructor:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>$optimizer = new Twig_Extension_Optimizer(Twig_NodeVisitor_Optimizer::OPTIMIZE_FOR);
$twig->addExtension($optimizer);
</pre></div>
</div>
<p>Twig supports the following optimizations:</p>
<ul class="simple">
<li><code class="docutils literal"><span class="pre">Twig_NodeVisitor_Optimizer::OPTIMIZE_ALL</span></code>, enables all optimizations
(this is the default value).</li>
<li><code class="docutils literal"><span class="pre">Twig_NodeVisitor_Optimizer::OPTIMIZE_NONE</span></code>, disables all optimizations.
This reduces the compilation time, but it can increase the execution time
and the consumed memory.</li>
<li><code class="docutils literal"><span class="pre">Twig_NodeVisitor_Optimizer::OPTIMIZE_FOR</span></code>, optimizes the <code class="docutils literal"><span class="pre">for</span></code> tag by
removing the <code class="docutils literal"><span class="pre">loop</span></code> variable creation whenever possible.</li>
<li><code class="docutils literal"><span class="pre">Twig_NodeVisitor_Optimizer::OPTIMIZE_RAW_FILTER</span></code>, removes the <code class="docutils literal"><span class="pre">raw</span></code>
filter whenever possible.</li>
<li><code class="docutils literal"><span class="pre">Twig_NodeVisitor_Optimizer::OPTIMIZE_VAR_ACCESS</span></code>, simplifies the creation
and access of variables in the compiled templates whenever possible.</li>
</ul>
</div>
</div>
<div class="section" id="exceptions">
<h2>Exceptions<a class="headerlink" href="#exceptions" title="Permalink to this headline">¶</a></h2>
<p>Twig can throw exceptions:</p>
<ul class="simple">
<li><code class="docutils literal"><span class="pre">Twig_Error</span></code>: The base exception for all errors.</li>
<li><code class="docutils literal"><span class="pre">Twig_Error_Syntax</span></code>: Thrown to tell the user that there is a problem with
the template syntax.</li>
<li><code class="docutils literal"><span class="pre">Twig_Error_Runtime</span></code>: Thrown when an error occurs at runtime (when a filter
does not exist for instance).</li>
<li><code class="docutils literal"><span class="pre">Twig_Error_Loader</span></code>: Thrown when an error occurs during template loading.</li>
<li><code class="docutils literal"><span class="pre">Twig_Sandbox_SecurityError</span></code>: Thrown when an unallowed tag, filter, or
method is called in a sandboxed template.</li>
</ul>
</div>
</div>
</div>
</div>
</div>
<div class="sphinxsidebar" role="navigation" aria-label="main navigation">
<div class="sphinxsidebarwrapper">
<h3><a href="index.html">Table Of Contents</a></h3>
<ul>
<li><a class="reference internal" href="#">Twig for Developers</a><ul>
<li><a class="reference internal" href="#basics">Basics</a></li>
<li><a class="reference internal" href="#rendering-templates">Rendering Templates</a></li>
<li><a class="reference internal" href="#environment-options">Environment Options</a></li>
<li><a class="reference internal" href="#loaders">Loaders</a><ul>
<li><a class="reference internal" href="#compilation-cache">Compilation Cache</a></li>
<li><a class="reference internal" href="#built-in-loaders">Built-in Loaders</a><ul>
<li><a class="reference internal" href="#twig-loader-filesystem"><code class="docutils literal"><span class="pre">Twig_Loader_Filesystem</span></code></a></li>
<li><a class="reference internal" href="#twig-loader-array"><code class="docutils literal"><span class="pre">Twig_Loader_Array</span></code></a></li>
<li><a class="reference internal" href="#twig-loader-chain"><code class="docutils literal"><span class="pre">Twig_Loader_Chain</span></code></a></li>
</ul>
</li>
<li><a class="reference internal" href="#create-your-own-loader">Create your own Loader</a></li>
</ul>
</li>
<li><a class="reference internal" href="#using-extensions">Using Extensions</a></li>
<li><a class="reference internal" href="#built-in-extensions">Built-in Extensions</a><ul>
<li><a class="reference internal" href="#core-extension">Core Extension</a></li>
<li><a class="reference internal" href="#escaper-extension">Escaper Extension</a></li>
<li><a class="reference internal" href="#sandbox-extension">Sandbox Extension</a></li>
<li><a class="reference internal" href="#profiler-extension">Profiler Extension</a></li>
<li><a class="reference internal" href="#optimizer-extension">Optimizer Extension</a></li>
</ul>
</li>
<li><a class="reference internal" href="#exceptions">Exceptions</a></li>
</ul>
</li>
</ul>
<h4>Previous topic</h4>
<p class="topless"><a href="templates.html"
title="previous chapter">Twig for Template Designers</a></p>
<h4>Next topic</h4>
<p class="topless"><a href="advanced.html"
title="next chapter">Extending Twig</a></p>
<div role="note" aria-label="source link">
<h3>This Page</h3>
<ul class="this-page-menu">
<li><a href="_sources/api.rst.txt"
rel="nofollow">Show Source</a></li>
</ul>
</div>
<div id="searchbox" style="display: none" role="search">
<h3>Quick search</h3>
<form class="search" action="search.html" method="get">
<div><input type="text" name="q" /></div>
<div><input type="submit" value="Go" /></div>
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
</div>
</div>
<div class="clearer"></div>
</div>
<div class="related" role="navigation" aria-label="related navigation">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="genindex.html" title="General Index"
>index</a></li>
<li class="right" >
<a href="advanced.html" title="Extending Twig"
>next</a> |</li>
<li class="right" >
<a href="templates.html" title="Twig for Template Designers"
>previous</a> |</li>
<li class="nav-item nav-item-0"><a href="index.html">php-twig-doc 2.4.6 documentation</a> »</li>
</ul>
</div>
<div class="footer" role="contentinfo">
© Copyright by the Twig Team.
Created using <a href="http://sphinx-doc.org/">Sphinx</a> 1.6.7.
</div>
</body>
</html>
|