/usr/share/doc/php-twig/manual/recipes.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 | <!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>Recipes — 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="Coding Standards" href="coding_standards.html" />
<link rel="prev" title="Twig Internals" href="internals.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="coding_standards.html" title="Coding Standards"
accesskey="N">next</a> |</li>
<li class="right" >
<a href="internals.html" title="Twig Internals"
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="recipes">
<h1>Recipes<a class="headerlink" href="#recipes" title="Permalink to this headline">¶</a></h1>
<div class="section" id="displaying-deprecation-notices">
<span id="deprecation-notices"></span><h2>Displaying Deprecation Notices<a class="headerlink" href="#displaying-deprecation-notices" title="Permalink to this headline">¶</a></h2>
<p>Deprecated features generate deprecation notices (via a call to the
<code class="docutils literal"><span class="pre">trigger_error()</span></code> PHP function). By default, they are silenced and never
displayed nor logged.</p>
<p>To easily remove all deprecated feature usages from your templates, write and
run a script along the lines of the following:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>require_once __DIR__.'/vendor/autoload.php';
$twig = create_your_twig_env();
$deprecations = new Twig_Util_DeprecationCollector($twig);
print_r($deprecations->collectDir(__DIR__.'/templates'));
</pre></div>
</div>
<p>The <code class="docutils literal"><span class="pre">collectDir()</span></code> method compiles all templates found in a directory,
catches deprecation notices, and return them.</p>
<div class="admonition tip">
<p class="first admonition-title">Tip</p>
<p class="last">If your templates are not stored on the filesystem, use the <code class="docutils literal"><span class="pre">collect()</span></code>
method instead. <code class="docutils literal"><span class="pre">collect()</span></code> takes a <code class="docutils literal"><span class="pre">Traversable</span></code> which must return
template names as keys and template contents as values (as done by
<code class="docutils literal"><span class="pre">Twig_Util_TemplateDirIterator</span></code>).</p>
</div>
<p>However, this code won’t find all deprecations (like using deprecated some Twig
classes). To catch all notices, register a custom error handler like the one
below:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>$deprecations = array();
set_error_handler(function ($type, $msg) use (&$deprecations) {
if (E_USER_DEPRECATED === $type) {
$deprecations[] = $msg;
}
});
// run your application
print_r($deprecations);
</pre></div>
</div>
<p>Note that most deprecation notices are triggered during <strong>compilation</strong>, so
they won’t be generated when templates are already cached.</p>
<div class="admonition tip">
<p class="first admonition-title">Tip</p>
<p class="last">If you want to manage the deprecation notices from your PHPUnit tests, have
a look at the <a class="reference external" href="https://github.com/symfony/phpunit-bridge">symfony/phpunit-bridge</a> package, which eases the
process a lot.</p>
</div>
</div>
<div class="section" id="making-a-layout-conditional">
<h2>Making a Layout conditional<a class="headerlink" href="#making-a-layout-conditional" title="Permalink to this headline">¶</a></h2>
<p>Working with Ajax means that the same content is sometimes displayed as is,
and sometimes decorated with a layout. As Twig layout template names can be
any valid expression, you can pass a variable that evaluates to <code class="docutils literal"><span class="pre">true</span></code> when
the request is made via Ajax and choose the layout accordingly:</p>
<div class="highlight-jinja"><div class="highlight"><pre><span></span><span class="cp">{%</span> <span class="k">extends</span> <span class="nv">request.ajax</span> <span class="p">?</span> <span class="s2">"base_ajax.html"</span> <span class="o">:</span> <span class="s2">"base.html"</span> <span class="cp">%}</span><span class="x"></span>
<span class="cp">{%</span> <span class="k">block</span> <span class="nv">content</span> <span class="cp">%}</span><span class="x"></span>
<span class="x"> This is the content to be displayed.</span>
<span class="cp">{%</span> <span class="k">endblock</span> <span class="cp">%}</span><span class="x"></span>
</pre></div>
</div>
</div>
<div class="section" id="making-an-include-dynamic">
<h2>Making an Include dynamic<a class="headerlink" href="#making-an-include-dynamic" title="Permalink to this headline">¶</a></h2>
<p>When including a template, its name does not need to be a string. For
instance, the name can depend on the value of a variable:</p>
<div class="highlight-jinja"><div class="highlight"><pre><span></span><span class="cp">{%</span> <span class="k">include</span> <span class="nv">var</span> <span class="o">~</span> <span class="s1">'_foo.html'</span> <span class="cp">%}</span><span class="x"></span>
</pre></div>
</div>
<p>If <code class="docutils literal"><span class="pre">var</span></code> evaluates to <code class="docutils literal"><span class="pre">index</span></code>, the <code class="docutils literal"><span class="pre">index_foo.html</span></code> template will be
rendered.</p>
<p>As a matter of fact, the template name can be any valid expression, such as
the following:</p>
<div class="highlight-jinja"><div class="highlight"><pre><span></span><span class="cp">{%</span> <span class="k">include</span> <span class="nv">var</span><span class="o">|</span><span class="nf">default</span><span class="o">(</span><span class="s1">'index'</span><span class="o">)</span> <span class="o">~</span> <span class="s1">'_foo.html'</span> <span class="cp">%}</span><span class="x"></span>
</pre></div>
</div>
</div>
<div class="section" id="overriding-a-template-that-also-extends-itself">
<h2>Overriding a Template that also extends itself<a class="headerlink" href="#overriding-a-template-that-also-extends-itself" title="Permalink to this headline">¶</a></h2>
<p>A template can be customized in two different ways:</p>
<ul class="simple">
<li><em>Inheritance</em>: A template <em>extends</em> a parent template and overrides some
blocks;</li>
<li><em>Replacement</em>: If you use the filesystem loader, Twig loads the first
template it finds in a list of configured directories; a template found in a
directory <em>replaces</em> another one from a directory further in the list.</li>
</ul>
<p>But how do you combine both: <em>replace</em> a template that also extends itself
(aka a template in a directory further in the list)?</p>
<p>Let’s say that your templates are loaded from both <code class="docutils literal"><span class="pre">.../templates/mysite</span></code>
and <code class="docutils literal"><span class="pre">.../templates/default</span></code> in this order. The <code class="docutils literal"><span class="pre">page.twig</span></code> template,
stored in <code class="docutils literal"><span class="pre">.../templates/default</span></code> reads as follows:</p>
<div class="highlight-jinja"><div class="highlight"><pre><span></span><span class="c">{# page.twig #}</span><span class="x"></span>
<span class="cp">{%</span> <span class="k">extends</span> <span class="s2">"layout.twig"</span> <span class="cp">%}</span><span class="x"></span>
<span class="cp">{%</span> <span class="k">block</span> <span class="nv">content</span> <span class="cp">%}</span><span class="x"></span>
<span class="cp">{%</span> <span class="k">endblock</span> <span class="cp">%}</span><span class="x"></span>
</pre></div>
</div>
<p>You can replace this template by putting a file with the same name in
<code class="docutils literal"><span class="pre">.../templates/mysite</span></code>. And if you want to extend the original template, you
might be tempted to write the following:</p>
<div class="highlight-jinja"><div class="highlight"><pre><span></span><span class="c">{# page.twig in .../templates/mysite #}</span><span class="x"></span>
<span class="cp">{%</span> <span class="k">extends</span> <span class="s2">"page.twig"</span> <span class="cp">%}</span><span class="x"> </span><span class="c">{# from .../templates/default #}</span><span class="x"></span>
</pre></div>
</div>
<p>Of course, this will not work as Twig will always load the template from
<code class="docutils literal"><span class="pre">.../templates/mysite</span></code>.</p>
<p>It turns out it is possible to get this to work, by adding a directory right
at the end of your template directories, which is the parent of all of the
other directories: <code class="docutils literal"><span class="pre">.../templates</span></code> in our case. This has the effect of
making every template file within our system uniquely addressable. Most of the
time you will use the “normal” paths, but in the special case of wanting to
extend a template with an overriding version of itself we can reference its
parent’s full, unambiguous template path in the extends tag:</p>
<div class="highlight-jinja"><div class="highlight"><pre><span></span><span class="c">{# page.twig in .../templates/mysite #}</span><span class="x"></span>
<span class="cp">{%</span> <span class="k">extends</span> <span class="s2">"default/page.twig"</span> <span class="cp">%}</span><span class="x"> </span><span class="c">{# from .../templates #}</span><span class="x"></span>
</pre></div>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">This recipe was inspired by the following Django wiki page:
<a class="reference external" href="http://code.djangoproject.com/wiki/ExtendingTemplates">http://code.djangoproject.com/wiki/ExtendingTemplates</a></p>
</div>
</div>
<div class="section" id="customizing-the-syntax">
<h2>Customizing the Syntax<a class="headerlink" href="#customizing-the-syntax" title="Permalink to this headline">¶</a></h2>
<p>Twig allows some syntax customization for the block delimiters. It’s not
recommended to use this feature as templates will be tied with your custom
syntax. But for specific projects, it can make sense to change the defaults.</p>
<p>To change the block delimiters, you need to create your own lexer object:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>$twig = new Twig_Environment(...);
$lexer = new Twig_Lexer($twig, array(
'tag_comment' => array('{#', '#}'),
'tag_block' => array('{%', '%}'),
'tag_variable' => array('{{', '}}'),
'interpolation' => array('#{', '}'),
));
$twig->setLexer($lexer);
</pre></div>
</div>
<p>Here are some configuration example that simulates some other template engines
syntax:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>// Ruby erb syntax
$lexer = new Twig_Lexer($twig, array(
'tag_comment' => array('<%#', '%>'),
'tag_block' => array('<%', '%>'),
'tag_variable' => array('<%=', '%>'),
));
// SGML Comment Syntax
$lexer = new Twig_Lexer($twig, array(
'tag_comment' => array('<!--#', '-->'),
'tag_block' => array('<!--', '-->'),
'tag_variable' => array('${', '}'),
));
// Smarty like
$lexer = new Twig_Lexer($twig, array(
'tag_comment' => array('{*', '*}'),
'tag_block' => array('{', '}'),
'tag_variable' => array('{$', '}'),
));
</pre></div>
</div>
</div>
<div class="section" id="using-dynamic-object-properties">
<h2>Using dynamic Object Properties<a class="headerlink" href="#using-dynamic-object-properties" title="Permalink to this headline">¶</a></h2>
<p>When Twig encounters a variable like <code class="docutils literal"><span class="pre">article.title</span></code>, it tries to find a
<code class="docutils literal"><span class="pre">title</span></code> public property in the <code class="docutils literal"><span class="pre">article</span></code> object.</p>
<p>It also works if the property does not exist but is rather defined dynamically
thanks to the magic <code class="docutils literal"><span class="pre">__get()</span></code> method; you just need to also implement the
<code class="docutils literal"><span class="pre">__isset()</span></code> magic method like shown in the following snippet of code:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>class Article
{
public function __get($name)
{
if ('title' == $name) {
return 'The title';
}
// throw some kind of error
}
public function __isset($name)
{
if ('title' == $name) {
return true;
}
return false;
}
}
</pre></div>
</div>
</div>
<div class="section" id="accessing-the-parent-context-in-nested-loops">
<h2>Accessing the parent Context in Nested Loops<a class="headerlink" href="#accessing-the-parent-context-in-nested-loops" title="Permalink to this headline">¶</a></h2>
<p>Sometimes, when using nested loops, you need to access the parent context. The
parent context is always accessible via the <code class="docutils literal"><span class="pre">loop.parent</span></code> variable. For
instance, if you have the following template data:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>$data = array(
'topics' => array(
'topic1' => array('Message 1 of topic 1', 'Message 2 of topic 1'),
'topic2' => array('Message 1 of topic 2', 'Message 2 of topic 2'),
),
);
</pre></div>
</div>
<p>And the following template to display all messages in all topics:</p>
<div class="highlight-jinja"><div class="highlight"><pre><span></span><span class="cp">{%</span> <span class="k">for</span> <span class="nv">topic</span><span class="o">,</span> <span class="nv">messages</span> <span class="k">in</span> <span class="nv">topics</span> <span class="cp">%}</span><span class="x"></span>
<span class="x"> * </span><span class="cp">{{</span> <span class="nb">loop</span><span class="nv">.index</span> <span class="cp">}}</span><span class="x">: </span><span class="cp">{{</span> <span class="nv">topic</span> <span class="cp">}}</span><span class="x"></span>
<span class="x"> </span><span class="cp">{%</span> <span class="k">for</span> <span class="nv">message</span> <span class="k">in</span> <span class="nv">messages</span> <span class="cp">%}</span><span class="x"></span>
<span class="x"> - </span><span class="cp">{{</span> <span class="nb">loop</span><span class="nv">.parent.loop.index</span> <span class="cp">}}</span><span class="x">.</span><span class="cp">{{</span> <span class="nb">loop</span><span class="nv">.index</span> <span class="cp">}}</span><span class="x">: </span><span class="cp">{{</span> <span class="nv">message</span> <span class="cp">}}</span><span class="x"></span>
<span class="x"> </span><span class="cp">{%</span> <span class="k">endfor</span> <span class="cp">%}</span><span class="x"></span>
<span class="cp">{%</span> <span class="k">endfor</span> <span class="cp">%}</span><span class="x"></span>
</pre></div>
</div>
<p>The output will be similar to:</p>
<div class="highlight-text"><div class="highlight"><pre><span></span>* 1: topic1
- 1.1: The message 1 of topic 1
- 1.2: The message 2 of topic 1
* 2: topic2
- 2.1: The message 1 of topic 2
- 2.2: The message 2 of topic 2
</pre></div>
</div>
<p>In the inner loop, the <code class="docutils literal"><span class="pre">loop.parent</span></code> variable is used to access the outer
context. So, the index of the current <code class="docutils literal"><span class="pre">topic</span></code> defined in the outer for loop
is accessible via the <code class="docutils literal"><span class="pre">loop.parent.loop.index</span></code> variable.</p>
</div>
<div class="section" id="defining-undefined-functions-and-filters-on-the-fly">
<h2>Defining undefined Functions and Filters on the Fly<a class="headerlink" href="#defining-undefined-functions-and-filters-on-the-fly" title="Permalink to this headline">¶</a></h2>
<p>When a function (or a filter) is not defined, Twig defaults to throw a
<code class="docutils literal"><span class="pre">Twig_Error_Syntax</span></code> exception. However, it can also call a <a class="reference external" href="http://www.php.net/manual/en/function.is-callable.php">callback</a> (any
valid PHP callable) which should return a function (or a filter).</p>
<p>For filters, register callbacks with <code class="docutils literal"><span class="pre">registerUndefinedFilterCallback()</span></code>.
For functions, use <code class="docutils literal"><span class="pre">registerUndefinedFunctionCallback()</span></code>:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>// auto-register all native PHP functions as Twig functions
// don't try this at home as it's not secure at all!
$twig->registerUndefinedFunctionCallback(function ($name) {
if (function_exists($name)) {
return new Twig_Function($name, $name);
}
return false;
});
</pre></div>
</div>
<p>If the callable is not able to return a valid function (or filter), it must
return <code class="docutils literal"><span class="pre">false</span></code>.</p>
<p>If you register more than one callback, Twig will call them in turn until one
does not return <code class="docutils literal"><span class="pre">false</span></code>.</p>
<div class="admonition tip">
<p class="first admonition-title">Tip</p>
<p class="last">As the resolution of functions and filters is done during compilation,
there is no overhead when registering these callbacks.</p>
</div>
</div>
<div class="section" id="validating-the-template-syntax">
<h2>Validating the Template Syntax<a class="headerlink" href="#validating-the-template-syntax" title="Permalink to this headline">¶</a></h2>
<p>When template code is provided by a third-party (through a web interface for
instance), it might be interesting to validate the template syntax before
saving it. If the template code is stored in a <cite>$template</cite> variable, here is
how you can do it:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>try {
$twig->parse($twig->tokenize(new Twig_Source($template)));
// the $template is valid
} catch (Twig_Error_Syntax $e) {
// $template contains one or more syntax errors
}
</pre></div>
</div>
<p>If you iterate over a set of files, you can pass the filename to the
<code class="docutils literal"><span class="pre">tokenize()</span></code> method to get the filename in the exception message:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>foreach ($files as $file) {
try {
$twig->parse($twig->tokenize(new Twig_Source($template, $file->getFilename(), $file)));
// the $template is valid
} catch (Twig_Error_Syntax $e) {
// $template contains one or more syntax errors
}
}
</pre></div>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">This method won’t catch any sandbox policy violations because the policy
is enforced during template rendering (as Twig needs the context for some
checks like allowed methods on objects).</p>
</div>
</div>
<div class="section" id="refreshing-modified-templates-when-opcache-or-apc-is-enabled">
<h2>Refreshing modified Templates when OPcache or APC is enabled<a class="headerlink" href="#refreshing-modified-templates-when-opcache-or-apc-is-enabled" title="Permalink to this headline">¶</a></h2>
<p>When using OPcache with <code class="docutils literal"><span class="pre">opcache.validate_timestamps</span></code> set to <code class="docutils literal"><span class="pre">0</span></code> or APC
with <code class="docutils literal"><span class="pre">apc.stat</span></code> set to <code class="docutils literal"><span class="pre">0</span></code> and Twig cache enabled, clearing the template
cache won’t update the cache.</p>
<p>To get around this, force Twig to invalidate the bytecode cache:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>$twig = new Twig_Environment($loader, array(
'cache' => new Twig_Cache_Filesystem('/some/cache/path', Twig_Cache_Filesystem::FORCE_BYTECODE_INVALIDATION),
// ...
));
</pre></div>
</div>
</div>
<div class="section" id="reusing-a-stateful-node-visitor">
<h2>Reusing a stateful Node Visitor<a class="headerlink" href="#reusing-a-stateful-node-visitor" title="Permalink to this headline">¶</a></h2>
<p>When attaching a visitor to a <code class="docutils literal"><span class="pre">Twig_Environment</span></code> instance, Twig uses it to
visit <em>all</em> templates it compiles. If you need to keep some state information
around, you probably want to reset it when visiting a new template.</p>
<p>This can be easily achieved with the following code:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>protected $someTemplateState = array();
public function enterNode(Twig_Node $node, Twig_Environment $env)
{
if ($node instanceof Twig_Node_Module) {
// reset the state as we are entering a new template
$this->someTemplateState = array();
}
// ...
return $node;
}
</pre></div>
</div>
</div>
<div class="section" id="using-a-database-to-store-templates">
<h2>Using a Database to store Templates<a class="headerlink" href="#using-a-database-to-store-templates" title="Permalink to this headline">¶</a></h2>
<p>If you are developing a CMS, templates are usually stored in a database. This
recipe gives you a simple PDO template loader you can use as a starting point
for your own.</p>
<p>First, let’s create a temporary in-memory SQLite3 database to work with:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>$dbh = new PDO('sqlite::memory:');
$dbh->exec('CREATE TABLE templates (name STRING, source STRING, last_modified INTEGER)');
$base = '{% block content %}{% endblock %}';
$index = '
{% extends "base.twig" %}
{% block content %}Hello {{ name }}{% endblock %}
';
$now = time();
$dbh->exec("INSERT INTO templates (name, source, last_modified) VALUES ('base.twig', '$base', $now)");
$dbh->exec("INSERT INTO templates (name, source, last_modified) VALUES ('index.twig', '$index', $now)");
</pre></div>
</div>
<p>We have created a simple <code class="docutils literal"><span class="pre">templates</span></code> table that hosts two templates:
<code class="docutils literal"><span class="pre">base.twig</span></code> and <code class="docutils literal"><span class="pre">index.twig</span></code>.</p>
<p>Now, let’s define a loader able to use this database:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>class DatabaseTwigLoader implements Twig_LoaderInterface
{
protected $dbh;
public function __construct(PDO $dbh)
{
$this->dbh = $dbh;
}
public function getSourceContext($name)
{
if (false === $source = $this->getValue('source', $name)) {
throw new Twig_Error_Loader(sprintf('Template "%s" does not exist.', $name));
}
return new Twig_Source($source, $name);
}
public function exists($name)
{
return $name === $this->getValue('name', $name);
}
public function getCacheKey($name)
{
return $name;
}
public function isFresh($name, $time)
{
if (false === $lastModified = $this->getValue('last_modified', $name)) {
return false;
}
return $lastModified <= $time;
}
protected function getValue($column, $name)
{
$sth = $this->dbh->prepare('SELECT '.$column.' FROM templates WHERE name = :name');
$sth->execute(array(':name' => (string) $name));
return $sth->fetchColumn();
}
}
</pre></div>
</div>
<p>Finally, here is an example on how you can use it:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>$loader = new DatabaseTwigLoader($dbh);
$twig = new Twig_Environment($loader);
echo $twig->render('index.twig', array('name' => 'Fabien'));
</pre></div>
</div>
</div>
<div class="section" id="using-different-template-sources">
<h2>Using different Template Sources<a class="headerlink" href="#using-different-template-sources" title="Permalink to this headline">¶</a></h2>
<p>This recipe is the continuation of the previous one. Even if you store the
contributed templates in a database, you might want to keep the original/base
templates on the filesystem. When templates can be loaded from different
sources, you need to use the <code class="docutils literal"><span class="pre">Twig_Loader_Chain</span></code> loader.</p>
<p>As you can see in the previous recipe, we reference the template in the exact
same way as we would have done it with a regular filesystem loader. This is
the key to be able to mix and match templates coming from the database, the
filesystem, or any other loader for that matter: the template name should be a
logical name, and not the path from the filesystem:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>$loader1 = new DatabaseTwigLoader($dbh);
$loader2 = new Twig_Loader_Array(array(
'base.twig' => '{% block content %}{% endblock %}',
));
$loader = new Twig_Loader_Chain(array($loader1, $loader2));
$twig = new Twig_Environment($loader);
echo $twig->render('index.twig', array('name' => 'Fabien'));
</pre></div>
</div>
<p>Now that the <code class="docutils literal"><span class="pre">base.twig</span></code> templates is defined in an array loader, you can
remove it from the database, and everything else will still work as before.</p>
</div>
<div class="section" id="loading-a-template-from-a-string">
<h2>Loading a Template from a String<a class="headerlink" href="#loading-a-template-from-a-string" title="Permalink to this headline">¶</a></h2>
<p>From a template, you can easily load a template stored in a string via the
<code class="docutils literal"><span class="pre">template_from_string</span></code> function (via the <code class="docutils literal"><span class="pre">Twig_Extension_StringLoader</span></code>
extension):</p>
<div class="highlight-jinja"><div class="highlight"><pre><span></span><span class="cp">{{</span> <span class="nv">include</span><span class="o">(</span><span class="nv">template_from_string</span><span class="o">(</span><span class="s2">"Hello {{ name }}"</span><span class="o">))</span> <span class="cp">}}</span><span class="x"></span>
</pre></div>
</div>
<p>From PHP, it’s also possible to load a template stored in a string via
<code class="docutils literal"><span class="pre">Twig_Environment::createTemplate()</span></code>:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>$template = $twig->createTemplate('hello {{ name }}');
echo $template->render(array('name' => 'Fabien'));
</pre></div>
</div>
</div>
<div class="section" id="using-twig-and-angularjs-in-the-same-templates">
<h2>Using Twig and AngularJS in the same Templates<a class="headerlink" href="#using-twig-and-angularjs-in-the-same-templates" title="Permalink to this headline">¶</a></h2>
<p>Mixing different template syntaxes in the same file is not a recommended
practice as both AngularJS and Twig use the same delimiters in their syntax:
<code class="docutils literal"><span class="pre">{{</span></code> and <code class="docutils literal"><span class="pre">}}</span></code>.</p>
<p>Still, if you want to use AngularJS and Twig in the same template, there are
two ways to make it work depending on the amount of AngularJS you need to
include in your templates:</p>
<ul>
<li><p class="first">Escaping the AngularJS delimiters by wrapping AngularJS sections with the
<code class="docutils literal"><span class="pre">{%</span> <span class="pre">verbatim</span> <span class="pre">%}</span></code> tag or by escaping each delimiter via <code class="docutils literal"><span class="pre">{{</span> <span class="pre">'{{'</span> <span class="pre">}}</span></code> and
<code class="docutils literal"><span class="pre">{{</span> <span class="pre">'}}'</span> <span class="pre">}}</span></code>;</p>
</li>
<li><p class="first">Changing the delimiters of one of the template engines (depending on which
engine you introduced last):</p>
<ul>
<li><p class="first">For AngularJS, change the interpolation tags using the
<code class="docutils literal"><span class="pre">interpolateProvider</span></code> service, for instance at the module initialization
time:</p>
<div class="highlight-javascript"><div class="highlight"><pre><span></span><span class="nx">angular</span><span class="p">.</span><span class="nx">module</span><span class="p">(</span><span class="s1">'myApp'</span><span class="p">,</span> <span class="p">[]).</span><span class="nx">config</span><span class="p">(</span><span class="kd">function</span><span class="p">(</span><span class="nx">$interpolateProvider</span><span class="p">)</span> <span class="p">{</span>
<span class="nx">$interpolateProvider</span><span class="p">.</span><span class="nx">startSymbol</span><span class="p">(</span><span class="s1">'{['</span><span class="p">).</span><span class="nx">endSymbol</span><span class="p">(</span><span class="s1">']}'</span><span class="p">);</span>
<span class="p">});</span>
</pre></div>
</div>
</li>
<li><p class="first">For Twig, change the delimiters via the <code class="docutils literal"><span class="pre">tag_variable</span></code> Lexer option:</p>
<div class="highlight-php"><div class="highlight"><pre><span></span><span class="x">$env->setLexer(new Twig_Lexer($env, array(</span>
<span class="x"> 'tag_variable' => array('{[', ']}'),</span>
<span class="x">)));</span>
</pre></div>
</div>
</li>
</ul>
</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="#">Recipes</a><ul>
<li><a class="reference internal" href="#displaying-deprecation-notices">Displaying Deprecation Notices</a></li>
<li><a class="reference internal" href="#making-a-layout-conditional">Making a Layout conditional</a></li>
<li><a class="reference internal" href="#making-an-include-dynamic">Making an Include dynamic</a></li>
<li><a class="reference internal" href="#overriding-a-template-that-also-extends-itself">Overriding a Template that also extends itself</a></li>
<li><a class="reference internal" href="#customizing-the-syntax">Customizing the Syntax</a></li>
<li><a class="reference internal" href="#using-dynamic-object-properties">Using dynamic Object Properties</a></li>
<li><a class="reference internal" href="#accessing-the-parent-context-in-nested-loops">Accessing the parent Context in Nested Loops</a></li>
<li><a class="reference internal" href="#defining-undefined-functions-and-filters-on-the-fly">Defining undefined Functions and Filters on the Fly</a></li>
<li><a class="reference internal" href="#validating-the-template-syntax">Validating the Template Syntax</a></li>
<li><a class="reference internal" href="#refreshing-modified-templates-when-opcache-or-apc-is-enabled">Refreshing modified Templates when OPcache or APC is enabled</a></li>
<li><a class="reference internal" href="#reusing-a-stateful-node-visitor">Reusing a stateful Node Visitor</a></li>
<li><a class="reference internal" href="#using-a-database-to-store-templates">Using a Database to store Templates</a></li>
<li><a class="reference internal" href="#using-different-template-sources">Using different Template Sources</a></li>
<li><a class="reference internal" href="#loading-a-template-from-a-string">Loading a Template from a String</a></li>
<li><a class="reference internal" href="#using-twig-and-angularjs-in-the-same-templates">Using Twig and AngularJS in the same Templates</a></li>
</ul>
</li>
</ul>
<h4>Previous topic</h4>
<p class="topless"><a href="internals.html"
title="previous chapter">Twig Internals</a></p>
<h4>Next topic</h4>
<p class="topless"><a href="coding_standards.html"
title="next chapter">Coding Standards</a></p>
<div role="note" aria-label="source link">
<h3>This Page</h3>
<ul class="this-page-menu">
<li><a href="_sources/recipes.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="coding_standards.html" title="Coding Standards"
>next</a> |</li>
<li class="right" >
<a href="internals.html" title="Twig Internals"
>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>
|