/usr/share/doc/php-twig/manual/advanced.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 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 | <!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>Extending Twig — 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="Twig Internals" href="internals.html" />
<link rel="prev" title="Twig for Developers" href="api.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="internals.html" title="Twig Internals"
accesskey="N">next</a> |</li>
<li class="right" >
<a href="api.html" title="Twig for Developers"
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="extending-twig">
<h1>Extending Twig<a class="headerlink" href="#extending-twig" title="Permalink to this headline">¶</a></h1>
<p>Twig can be extended in many ways; you can add extra tags, filters, tests,
operators, global variables, and functions. You can even extend the parser
itself with node visitors.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The first section of this chapter describes how to extend Twig easily. If
you want to reuse your changes in different projects or if you want to
share them with others, you should then create an extension as described
in the following section.</p>
</div>
<div class="admonition caution">
<p class="first admonition-title">Caution</p>
<p class="last">When extending Twig without creating an extension, Twig won’t be able to
recompile your templates when the PHP code is updated. To see your changes
in real-time, either disable template caching or package your code into an
extension (see the next section of this chapter).</p>
</div>
<p>Before extending Twig, you must understand the differences between all the
different possible extension points and when to use them.</p>
<p>First, remember that Twig has two main language constructs:</p>
<ul class="simple">
<li><code class="docutils literal"><span class="pre">{{</span> <span class="pre">}}</span></code>: used to print the result of an expression evaluation;</li>
<li><code class="docutils literal"><span class="pre">{%</span> <span class="pre">%}</span></code>: used to execute statements.</li>
</ul>
<p>To understand why Twig exposes so many extension points, let’s see how to
implement a <em>Lorem ipsum</em> generator (it needs to know the number of words to
generate).</p>
<p>You can use a <code class="docutils literal"><span class="pre">lipsum</span></code> <em>tag</em>:</p>
<div class="highlight-jinja"><div class="highlight"><pre><span></span><span class="cp">{%</span> <span class="k">lipsum</span> <span class="m">40</span> <span class="cp">%}</span><span class="x"></span>
</pre></div>
</div>
<p>That works, but using a tag for <code class="docutils literal"><span class="pre">lipsum</span></code> is not a good idea for at least
three main reasons:</p>
<ul>
<li><p class="first"><code class="docutils literal"><span class="pre">lipsum</span></code> is not a language construct;</p>
</li>
<li><p class="first">The tag outputs something;</p>
</li>
<li><p class="first">The tag is not flexible as you cannot use it in an expression:</p>
<div class="highlight-jinja"><div class="highlight"><pre><span></span>{{ 'some text' ~ {% lipsum 40 %} ~ 'some more text' }}
</pre></div>
</div>
</li>
</ul>
<p>In fact, you rarely need to create tags; and that’s good news because tags are
the most complex extension point of Twig.</p>
<p>Now, let’s use a <code class="docutils literal"><span class="pre">lipsum</span></code> <em>filter</em>:</p>
<div class="highlight-jinja"><div class="highlight"><pre><span></span><span class="cp">{{</span> <span class="m">40</span><span class="o">|</span><span class="nf">lipsum</span> <span class="cp">}}</span><span class="x"></span>
</pre></div>
</div>
<p>Again, it works, but it looks weird. A filter transforms the passed value to
something else but here we use the value to indicate the number of words to
generate (so, <code class="docutils literal"><span class="pre">40</span></code> is an argument of the filter, not the value we want to
transform).</p>
<p>Next, let’s use a <code class="docutils literal"><span class="pre">lipsum</span></code> <em>function</em>:</p>
<div class="highlight-jinja"><div class="highlight"><pre><span></span><span class="cp">{{</span> <span class="nv">lipsum</span><span class="o">(</span><span class="m">40</span><span class="o">)</span> <span class="cp">}}</span><span class="x"></span>
</pre></div>
</div>
<p>Here we go. For this specific example, the creation of a function is the
extension point to use. And you can use it anywhere an expression is accepted:</p>
<div class="highlight-jinja"><div class="highlight"><pre><span></span><span class="cp">{{</span> <span class="s1">'some text'</span> <span class="o">~</span> <span class="nv">lipsum</span><span class="o">(</span><span class="m">40</span><span class="o">)</span> <span class="o">~</span> <span class="s1">'some more text'</span> <span class="cp">}}</span><span class="x"></span>
<span class="cp">{%</span> <span class="k">set</span> <span class="nv">lipsum</span> <span class="o">=</span> <span class="nv">lipsum</span><span class="o">(</span><span class="m">40</span><span class="o">)</span> <span class="cp">%}</span><span class="x"></span>
</pre></div>
</div>
<p>Last but not the least, you can also use a <em>global</em> object with a method able
to generate lorem ipsum text:</p>
<div class="highlight-jinja"><div class="highlight"><pre><span></span><span class="cp">{{</span> <span class="nv">text.lipsum</span><span class="o">(</span><span class="m">40</span><span class="o">)</span> <span class="cp">}}</span><span class="x"></span>
</pre></div>
</div>
<p>As a rule of thumb, use functions for frequently used features and global
objects for everything else.</p>
<p>Keep in mind the following when you want to extend Twig:</p>
<table border="1" class="docutils">
<colgroup>
<col width="14%" />
<col width="37%" />
<col width="14%" />
<col width="35%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">What?</th>
<th class="head">Implementation difficulty?</th>
<th class="head">How often?</th>
<th class="head">When?</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><em>macro</em></td>
<td>trivial</td>
<td>frequent</td>
<td>Content generation</td>
</tr>
<tr class="row-odd"><td><em>global</em></td>
<td>trivial</td>
<td>frequent</td>
<td>Helper object</td>
</tr>
<tr class="row-even"><td><em>function</em></td>
<td>trivial</td>
<td>frequent</td>
<td>Content generation</td>
</tr>
<tr class="row-odd"><td><em>filter</em></td>
<td>trivial</td>
<td>frequent</td>
<td>Value transformation</td>
</tr>
<tr class="row-even"><td><em>tag</em></td>
<td>complex</td>
<td>rare</td>
<td>DSL language construct</td>
</tr>
<tr class="row-odd"><td><em>test</em></td>
<td>trivial</td>
<td>rare</td>
<td>Boolean decision</td>
</tr>
<tr class="row-even"><td><em>operator</em></td>
<td>trivial</td>
<td>rare</td>
<td>Values transformation</td>
</tr>
</tbody>
</table>
<div class="section" id="globals">
<h2>Globals<a class="headerlink" href="#globals" title="Permalink to this headline">¶</a></h2>
<p>A global variable is like any other template variable, except that it’s
available in all templates and macros:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>$twig = new Twig_Environment($loader);
$twig->addGlobal('text', new Text());
</pre></div>
</div>
<p>You can then use the <code class="docutils literal"><span class="pre">text</span></code> variable anywhere in a template:</p>
<div class="highlight-jinja"><div class="highlight"><pre><span></span><span class="cp">{{</span> <span class="nv">text.lipsum</span><span class="o">(</span><span class="m">40</span><span class="o">)</span> <span class="cp">}}</span><span class="x"></span>
</pre></div>
</div>
</div>
<div class="section" id="filters">
<h2>Filters<a class="headerlink" href="#filters" title="Permalink to this headline">¶</a></h2>
<p>Creating a filter is as simple as associating a name with a PHP callable:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>// an anonymous function
$filter = new Twig_Filter('rot13', function ($string) {
return str_rot13($string);
});
// or a simple PHP function
$filter = new Twig_Filter('rot13', 'str_rot13');
// or a class static method
$filter = new Twig_Filter('rot13', array('SomeClass', 'rot13Filter'));
$filter = new Twig_Filter('rot13', 'SomeClass::rot13Filter');
// or a class method
$filter = new Twig_Filter('rot13', array($this, 'rot13Filter'));
// the one below needs a runtime implementation (see below for more information)
$filter = new Twig_Filter('rot13', array('SomeClass', 'rot13Filter'));
</pre></div>
</div>
<p>The first argument passed to the <code class="docutils literal"><span class="pre">Twig_Filter</span></code> constructor is the name of the
filter you will use in templates and the second one is the PHP callable to
associate with it.</p>
<p>Then, add the filter to your Twig environment:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>$twig = new Twig_Environment($loader);
$twig->addFilter($filter);
</pre></div>
</div>
<p>And here is how to use it in a template:</p>
<div class="highlight-jinja"><div class="highlight"><pre><span></span><span class="cp">{{</span> <span class="s1">'Twig'</span><span class="o">|</span><span class="nf">rot13</span> <span class="cp">}}</span><span class="x"></span>
<span class="c">{# will output Gjvt #}</span><span class="x"></span>
</pre></div>
</div>
<p>When called by Twig, the PHP callable receives the left side of the filter
(before the pipe <code class="docutils literal"><span class="pre">|</span></code>) as the first argument and the extra arguments passed
to the filter (within parentheses <code class="docutils literal"><span class="pre">()</span></code>) as extra arguments.</p>
<p>For instance, the following code:</p>
<div class="highlight-jinja"><div class="highlight"><pre><span></span><span class="cp">{{</span> <span class="s1">'TWIG'</span><span class="o">|</span><span class="nf">lower</span> <span class="cp">}}</span><span class="x"></span>
<span class="cp">{{</span> <span class="nv">now</span><span class="o">|</span><span class="nf">date</span><span class="o">(</span><span class="s1">'d/m/Y'</span><span class="o">)</span> <span class="cp">}}</span><span class="x"></span>
</pre></div>
</div>
<p>is compiled to something like the following:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><?php echo strtolower('TWIG') ?>
<?php echo twig_date_format_filter($now, 'd/m/Y') ?>
</pre></div>
</div>
<p>The <code class="docutils literal"><span class="pre">Twig_Filter</span></code> class takes an array of options as its last argument:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>$filter = new Twig_Filter('rot13', 'str_rot13', $options);
</pre></div>
</div>
<div class="section" id="environment-aware-filters">
<h3>Environment-aware Filters<a class="headerlink" href="#environment-aware-filters" title="Permalink to this headline">¶</a></h3>
<p>If you want to access the current environment instance in your filter, set the
<code class="docutils literal"><span class="pre">needs_environment</span></code> option to <code class="docutils literal"><span class="pre">true</span></code>; Twig will pass the current
environment as the first argument to the filter call:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>$filter = new Twig_Filter('rot13', function (Twig_Environment $env, $string) {
// get the current charset for instance
$charset = $env->getCharset();
return str_rot13($string);
}, array('needs_environment' => true));
</pre></div>
</div>
</div>
<div class="section" id="context-aware-filters">
<h3>Context-aware Filters<a class="headerlink" href="#context-aware-filters" title="Permalink to this headline">¶</a></h3>
<p>If you want to access the current context in your filter, set the
<code class="docutils literal"><span class="pre">needs_context</span></code> option to <code class="docutils literal"><span class="pre">true</span></code>; Twig will pass the current context as
the first argument to the filter call (or the second one if
<code class="docutils literal"><span class="pre">needs_environment</span></code> is also set to <code class="docutils literal"><span class="pre">true</span></code>):</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>$filter = new Twig_Filter('rot13', function ($context, $string) {
// ...
}, array('needs_context' => true));
$filter = new Twig_Filter('rot13', function (Twig_Environment $env, $context, $string) {
// ...
}, array('needs_context' => true, 'needs_environment' => true));
</pre></div>
</div>
</div>
<div class="section" id="automatic-escaping">
<h3>Automatic Escaping<a class="headerlink" href="#automatic-escaping" title="Permalink to this headline">¶</a></h3>
<p>If automatic escaping is enabled, the output of the filter may be escaped
before printing. If your filter acts as an escaper (or explicitly outputs HTML
or JavaScript code), you will want the raw output to be printed. In such a
case, set the <code class="docutils literal"><span class="pre">is_safe</span></code> option:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>$filter = new Twig_Filter('nl2br', 'nl2br', array('is_safe' => array('html')));
</pre></div>
</div>
<p>Some filters may need to work on input that is already escaped or safe, for
example when adding (safe) HTML tags to originally unsafe output. In such a
case, set the <code class="docutils literal"><span class="pre">pre_escape</span></code> option to escape the input data before it is run
through your filter:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>$filter = new Twig_Filter('somefilter', 'somefilter', array('pre_escape' => 'html', 'is_safe' => array('html')));
</pre></div>
</div>
</div>
<div class="section" id="variadic-filters">
<h3>Variadic Filters<a class="headerlink" href="#variadic-filters" title="Permalink to this headline">¶</a></h3>
<p>When a filter should accept an arbitrary number of arguments, set the
<code class="docutils literal"><span class="pre">is_variadic</span></code> option to <code class="docutils literal"><span class="pre">true</span></code>; Twig will pass the extra arguments as the
last argument to the filter call as an array:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>$filter = new Twig_Filter('thumbnail', function ($file, array $options = array()) {
// ...
}, array('is_variadic' => true));
</pre></div>
</div>
<p>Be warned that named arguments passed to a variadic filter cannot be checked
for validity as they will automatically end up in the option array.</p>
</div>
<div class="section" id="dynamic-filters">
<h3>Dynamic Filters<a class="headerlink" href="#dynamic-filters" title="Permalink to this headline">¶</a></h3>
<p>A filter name containing the special <code class="docutils literal"><span class="pre">*</span></code> character is a dynamic filter as
the <code class="docutils literal"><span class="pre">*</span></code> can be any string:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>$filter = new Twig_Filter('*_path', function ($name, $arguments) {
// ...
});
</pre></div>
</div>
<p>The following filters will be matched by the above defined dynamic filter:</p>
<ul class="simple">
<li><code class="docutils literal"><span class="pre">product_path</span></code></li>
<li><code class="docutils literal"><span class="pre">category_path</span></code></li>
</ul>
<p>A dynamic filter can define more than one dynamic parts:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>$filter = new Twig_Filter('*_path_*', function ($name, $suffix, $arguments) {
// ...
});
</pre></div>
</div>
<p>The filter will receive all dynamic part values before the normal filter
arguments, but after the environment and the context. For instance, a call to
<code class="docutils literal"><span class="pre">'foo'|a_path_b()</span></code> will result in the following arguments to be passed to
the filter: <code class="docutils literal"><span class="pre">('a',</span> <span class="pre">'b',</span> <span class="pre">'foo')</span></code>.</p>
</div>
<div class="section" id="deprecated-filters">
<h3>Deprecated Filters<a class="headerlink" href="#deprecated-filters" title="Permalink to this headline">¶</a></h3>
<p>You can mark a filter as being deprecated by setting the <code class="docutils literal"><span class="pre">deprecated</span></code> option
to <code class="docutils literal"><span class="pre">true</span></code>. You can also give an alternative filter that replaces the
deprecated one when that makes sense:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>$filter = new Twig_Filter('obsolete', function () {
// ...
}, array('deprecated' => true, 'alternative' => 'new_one'));
</pre></div>
</div>
<p>When a filter is deprecated, Twig emits a deprecation notice when compiling a
template using it. See <a class="reference internal" href="recipes.html#deprecation-notices"><span class="std std-ref">Displaying Deprecation Notices</span></a> for more information.</p>
</div>
</div>
<div class="section" id="functions">
<h2>Functions<a class="headerlink" href="#functions" title="Permalink to this headline">¶</a></h2>
<p>Functions are defined in the exact same way as filters, but you need to create
an instance of <code class="docutils literal"><span class="pre">Twig_Function</span></code>:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>$twig = new Twig_Environment($loader);
$function = new Twig_Function('function_name', function () {
// ...
});
$twig->addFunction($function);
</pre></div>
</div>
<p>Functions support the same features as filters, except for the <code class="docutils literal"><span class="pre">pre_escape</span></code>
and <code class="docutils literal"><span class="pre">preserves_safety</span></code> options.</p>
</div>
<div class="section" id="tests">
<h2>Tests<a class="headerlink" href="#tests" title="Permalink to this headline">¶</a></h2>
<p>Tests are defined in the exact same way as filters and functions, but you need
to create an instance of <code class="docutils literal"><span class="pre">Twig_Test</span></code>:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>$twig = new Twig_Environment($loader);
$test = new Twig_Test('test_name', function () {
// ...
});
$twig->addTest($test);
</pre></div>
</div>
<p>Tests allow you to create custom application specific logic for evaluating
boolean conditions. As a simple example, let’s create a Twig test that checks if
objects are ‘red’:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>$twig = new Twig_Environment($loader);
$test = new Twig_Test('red', function ($value) {
if (isset($value->color) && $value->color == 'red') {
return true;
}
if (isset($value->paint) && $value->paint == 'red') {
return true;
}
return false;
});
$twig->addTest($test);
</pre></div>
</div>
<p>Test functions should always return true/false.</p>
<p>When creating tests you can use the <code class="docutils literal"><span class="pre">node_class</span></code> option to provide custom test
compilation. This is useful if your test can be compiled into PHP primitives.
This is used by many of the tests built into Twig:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>$twig = new Twig_Environment($loader);
$test = new Twig_Test(
'odd',
null,
array('node_class' => 'Twig_Node_Expression_Test_Odd'));
$twig->addTest($test);
class Twig_Node_Expression_Test_Odd extends Twig_Node_Expression_Test
{
public function compile(Twig_Compiler $compiler)
{
$compiler
->raw('(')
->subcompile($this->getNode('node'))
->raw(' % 2 == 1')
->raw(')')
;
}
}
</pre></div>
</div>
<p>The above example shows how you can create tests that use a node class. The
node class has access to one sub-node called ‘node’. This sub-node contains the
value that is being tested. When the <code class="docutils literal"><span class="pre">odd</span></code> filter is used in code such as:</p>
<div class="highlight-jinja"><div class="highlight"><pre><span></span><span class="cp">{%</span> <span class="k">if</span> <span class="nv">my_value</span> <span class="k">is</span> <span class="nf">odd</span> <span class="cp">%}</span><span class="x"></span>
</pre></div>
</div>
<p>The <code class="docutils literal"><span class="pre">node</span></code> sub-node will contain an expression of <code class="docutils literal"><span class="pre">my_value</span></code>. Node-based
tests also have access to the <code class="docutils literal"><span class="pre">arguments</span></code> node. This node will contain the
various other arguments that have been provided to your test.</p>
<p>If you want to pass a variable number of positional or named arguments to the
test, set the <code class="docutils literal"><span class="pre">is_variadic</span></code> option to <code class="docutils literal"><span class="pre">true</span></code>. Tests also support dynamic
name feature as filters and functions.</p>
</div>
<div class="section" id="tags">
<h2>Tags<a class="headerlink" href="#tags" title="Permalink to this headline">¶</a></h2>
<p>One of the most exciting features of a template engine like Twig is the
possibility to define new language constructs. This is also the most complex
feature as you need to understand how Twig’s internals work.</p>
<p>Let’s create a simple <code class="docutils literal"><span class="pre">set</span></code> tag that allows the definition of simple
variables from within a template. The tag can be used like follows:</p>
<div class="highlight-jinja"><div class="highlight"><pre><span></span><span class="cp">{%</span> <span class="k">set</span> <span class="nv">name</span> <span class="o">=</span> <span class="s2">"value"</span> <span class="cp">%}</span><span class="x"></span>
<span class="cp">{{</span> <span class="nv">name</span> <span class="cp">}}</span><span class="x"></span>
<span class="c">{# should output value #}</span><span class="x"></span>
</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">set</span></code> tag is part of the Core extension and as such is always
available. The built-in version is slightly more powerful and supports
multiple assignments by default (cf. the template designers chapter for
more information).</p>
</div>
<p>Three steps are needed to define a new tag:</p>
<ul class="simple">
<li>Defining a Token Parser class (responsible for parsing the template code);</li>
<li>Defining a Node class (responsible for converting the parsed code to PHP);</li>
<li>Registering the tag.</li>
</ul>
<div class="section" id="registering-a-new-tag">
<h3>Registering a new tag<a class="headerlink" href="#registering-a-new-tag" title="Permalink to this headline">¶</a></h3>
<p>Adding a tag is as simple as calling the <code class="docutils literal"><span class="pre">addTokenParser</span></code> method on the
<code class="docutils literal"><span class="pre">Twig_Environment</span></code> instance:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>$twig = new Twig_Environment($loader);
$twig->addTokenParser(new Project_Set_TokenParser());
</pre></div>
</div>
</div>
<div class="section" id="defining-a-token-parser">
<h3>Defining a Token Parser<a class="headerlink" href="#defining-a-token-parser" title="Permalink to this headline">¶</a></h3>
<p>Now, let’s see the actual code of this class:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>class Project_Set_TokenParser extends Twig_TokenParser
{
public function parse(Twig_Token $token)
{
$parser = $this->parser;
$stream = $parser->getStream();
$name = $stream->expect(Twig_Token::NAME_TYPE)->getValue();
$stream->expect(Twig_Token::OPERATOR_TYPE, '=');
$value = $parser->getExpressionParser()->parseExpression();
$stream->expect(Twig_Token::BLOCK_END_TYPE);
return new Project_Set_Node($name, $value, $token->getLine(), $this->getTag());
}
public function getTag()
{
return 'set';
}
}
</pre></div>
</div>
<p>The <code class="docutils literal"><span class="pre">getTag()</span></code> method must return the tag we want to parse, here <code class="docutils literal"><span class="pre">set</span></code>.</p>
<p>The <code class="docutils literal"><span class="pre">parse()</span></code> method is invoked whenever the parser encounters a <code class="docutils literal"><span class="pre">set</span></code>
tag. It should return a <code class="docutils literal"><span class="pre">Twig_Node</span></code> instance that represents the node (the
<code class="docutils literal"><span class="pre">Project_Set_Node</span></code> calls creating is explained in the next section).</p>
<p>The parsing process is simplified thanks to a bunch of methods you can call
from the token stream (<code class="docutils literal"><span class="pre">$this->parser->getStream()</span></code>):</p>
<ul class="simple">
<li><code class="docutils literal"><span class="pre">getCurrent()</span></code>: Gets the current token in the stream.</li>
<li><code class="docutils literal"><span class="pre">next()</span></code>: Moves to the next token in the stream, <em>but returns the old one</em>.</li>
<li><code class="docutils literal"><span class="pre">test($type)</span></code>, <code class="docutils literal"><span class="pre">test($value)</span></code> or <code class="docutils literal"><span class="pre">test($type,</span> <span class="pre">$value)</span></code>: Determines whether
the current token is of a particular type or value (or both). The value may be an
array of several possible values.</li>
<li><code class="docutils literal"><span class="pre">expect($type[,</span> <span class="pre">$value[,</span> <span class="pre">$message]])</span></code>: If the current token isn’t of the given
type/value a syntax error is thrown. Otherwise, if the type and value are correct,
the token is returned and the stream moves to the next token.</li>
<li><code class="docutils literal"><span class="pre">look()</span></code>: Looks at the next token without consuming it.</li>
</ul>
<p>Parsing expressions is done by calling the <code class="docutils literal"><span class="pre">parseExpression()</span></code> like we did for
the <code class="docutils literal"><span class="pre">set</span></code> tag.</p>
<div class="admonition tip">
<p class="first admonition-title">Tip</p>
<p class="last">Reading the existing <code class="docutils literal"><span class="pre">TokenParser</span></code> classes is the best way to learn all
the nitty-gritty details of the parsing process.</p>
</div>
</div>
<div class="section" id="defining-a-node">
<h3>Defining a Node<a class="headerlink" href="#defining-a-node" title="Permalink to this headline">¶</a></h3>
<p>The <code class="docutils literal"><span class="pre">Project_Set_Node</span></code> class itself is rather simple:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>class Project_Set_Node extends Twig_Node
{
public function __construct($name, Twig_Node_Expression $value, $line, $tag = null)
{
parent::__construct(array('value' => $value), array('name' => $name), $line, $tag);
}
public function compile(Twig_Compiler $compiler)
{
$compiler
->addDebugInfo($this)
->write('$context[\''.$this->getAttribute('name').'\'] = ')
->subcompile($this->getNode('value'))
->raw(";\n")
;
}
}
</pre></div>
</div>
<p>The compiler implements a fluid interface and provides methods that helps the
developer generate beautiful and readable PHP code:</p>
<ul class="simple">
<li><code class="docutils literal"><span class="pre">subcompile()</span></code>: Compiles a node.</li>
<li><code class="docutils literal"><span class="pre">raw()</span></code>: Writes the given string as is.</li>
<li><code class="docutils literal"><span class="pre">write()</span></code>: Writes the given string by adding indentation at the beginning
of each line.</li>
<li><code class="docutils literal"><span class="pre">string()</span></code>: Writes a quoted string.</li>
<li><code class="docutils literal"><span class="pre">repr()</span></code>: Writes a PHP representation of a given value (see
<code class="docutils literal"><span class="pre">Twig_Node_For</span></code> for a usage example).</li>
<li><code class="docutils literal"><span class="pre">addDebugInfo()</span></code>: Adds the line of the original template file related to
the current node as a comment.</li>
<li><code class="docutils literal"><span class="pre">indent()</span></code>: Indents the generated code (see <code class="docutils literal"><span class="pre">Twig_Node_Block</span></code> for a
usage example).</li>
<li><code class="docutils literal"><span class="pre">outdent()</span></code>: Outdents the generated code (see <code class="docutils literal"><span class="pre">Twig_Node_Block</span></code> for a
usage example).</li>
</ul>
</div>
</div>
<div class="section" id="creating-an-extension">
<span id="creating-extensions"></span><h2>Creating an Extension<a class="headerlink" href="#creating-an-extension" title="Permalink to this headline">¶</a></h2>
<p>The main motivation for writing an extension is to move often used code into a
reusable class like adding support for internationalization. An extension can
define tags, filters, tests, operators, global variables, functions, and node
visitors.</p>
<p>Most of the time, it is useful to create a single extension for your project,
to host all the specific tags and filters you want to add to Twig.</p>
<div class="admonition tip">
<p class="first admonition-title">Tip</p>
<p class="last">When packaging your code into an extension, Twig is smart enough to
recompile your templates whenever you make a change to it (when
<code class="docutils literal"><span class="pre">auto_reload</span></code> is enabled).</p>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Before writing your own extensions, have a look at the Twig official
extension repository: <a class="reference external" href="http://github.com/twigphp/Twig-extensions">http://github.com/twigphp/Twig-extensions</a>.</p>
</div>
<p>An extension is a class that implements the following interface:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="n">interface</span> <span class="n">Twig_ExtensionInterface</span>
<span class="p">{</span>
<span class="o">/**</span>
<span class="o">*</span> <span class="n">Returns</span> <span class="n">the</span> <span class="n">token</span> <span class="n">parser</span> <span class="n">instances</span> <span class="n">to</span> <span class="n">add</span> <span class="n">to</span> <span class="n">the</span> <span class="n">existing</span> <span class="nb">list</span><span class="o">.</span>
<span class="o">*</span>
<span class="o">*</span> <span class="nd">@return</span> <span class="n">Twig_TokenParserInterface</span><span class="p">[]</span>
<span class="o">*/</span>
<span class="n">public</span> <span class="n">function</span> <span class="n">getTokenParsers</span><span class="p">();</span>
<span class="o">/**</span>
<span class="o">*</span> <span class="n">Returns</span> <span class="n">the</span> <span class="n">node</span> <span class="n">visitor</span> <span class="n">instances</span> <span class="n">to</span> <span class="n">add</span> <span class="n">to</span> <span class="n">the</span> <span class="n">existing</span> <span class="nb">list</span><span class="o">.</span>
<span class="o">*</span>
<span class="o">*</span> <span class="nd">@return</span> <span class="n">Twig_NodeVisitorInterface</span><span class="p">[]</span>
<span class="o">*/</span>
<span class="n">public</span> <span class="n">function</span> <span class="n">getNodeVisitors</span><span class="p">();</span>
<span class="o">/**</span>
<span class="o">*</span> <span class="n">Returns</span> <span class="n">a</span> <span class="nb">list</span> <span class="n">of</span> <span class="n">filters</span> <span class="n">to</span> <span class="n">add</span> <span class="n">to</span> <span class="n">the</span> <span class="n">existing</span> <span class="nb">list</span><span class="o">.</span>
<span class="o">*</span>
<span class="o">*</span> <span class="nd">@return</span> <span class="n">Twig_Filter</span><span class="p">[]</span>
<span class="o">*/</span>
<span class="n">public</span> <span class="n">function</span> <span class="n">getFilters</span><span class="p">();</span>
<span class="o">/**</span>
<span class="o">*</span> <span class="n">Returns</span> <span class="n">a</span> <span class="nb">list</span> <span class="n">of</span> <span class="n">tests</span> <span class="n">to</span> <span class="n">add</span> <span class="n">to</span> <span class="n">the</span> <span class="n">existing</span> <span class="nb">list</span><span class="o">.</span>
<span class="o">*</span>
<span class="o">*</span> <span class="nd">@return</span> <span class="n">Twig_Test</span><span class="p">[]</span>
<span class="o">*/</span>
<span class="n">public</span> <span class="n">function</span> <span class="n">getTests</span><span class="p">();</span>
<span class="o">/**</span>
<span class="o">*</span> <span class="n">Returns</span> <span class="n">a</span> <span class="nb">list</span> <span class="n">of</span> <span class="n">functions</span> <span class="n">to</span> <span class="n">add</span> <span class="n">to</span> <span class="n">the</span> <span class="n">existing</span> <span class="nb">list</span><span class="o">.</span>
<span class="o">*</span>
<span class="o">*</span> <span class="nd">@return</span> <span class="n">Twig_Function</span><span class="p">[]</span>
<span class="o">*/</span>
<span class="n">public</span> <span class="n">function</span> <span class="n">getFunctions</span><span class="p">();</span>
<span class="o">/**</span>
<span class="o">*</span> <span class="n">Returns</span> <span class="n">a</span> <span class="nb">list</span> <span class="n">of</span> <span class="n">operators</span> <span class="n">to</span> <span class="n">add</span> <span class="n">to</span> <span class="n">the</span> <span class="n">existing</span> <span class="nb">list</span><span class="o">.</span>
<span class="o">*</span>
<span class="o">*</span> <span class="nd">@return</span> <span class="n">array</span><span class="o"><</span><span class="n">array</span><span class="o">></span> <span class="n">First</span> <span class="n">array</span> <span class="n">of</span> <span class="n">unary</span> <span class="n">operators</span><span class="p">,</span> <span class="n">second</span> <span class="n">array</span> <span class="n">of</span> <span class="n">binary</span> <span class="n">operators</span>
<span class="o">*/</span>
<span class="n">public</span> <span class="n">function</span> <span class="n">getOperators</span><span class="p">();</span>
<span class="p">}</span>
</pre></div>
</div>
<p>To keep your extension class clean and lean, inherit from the built-in
<code class="docutils literal"><span class="pre">Twig_Extension</span></code> class instead of implementing the interface as it provides
empty implementations for all methods:</p>
<blockquote>
<div>class Project_Twig_Extension extends Twig_Extension
{
}</div></blockquote>
<p>Of course, this extension does nothing for now. We will customize it in the
next sections.</p>
<p>Twig does not care where you save your extension on the filesystem, as all
extensions must be registered explicitly to be available in your templates.</p>
<p>You can register an extension by using the <code class="docutils literal"><span class="pre">addExtension()</span></code> method on your
main <code class="docutils literal"><span class="pre">Environment</span></code> object:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>$twig = new Twig_Environment($loader);
$twig->addExtension(new Project_Twig_Extension());
</pre></div>
</div>
<div class="admonition tip">
<p class="first admonition-title">Tip</p>
<p class="last">The Twig core extensions are great examples of how extensions work.</p>
</div>
<div class="section" id="id1">
<h3>Globals<a class="headerlink" href="#id1" title="Permalink to this headline">¶</a></h3>
<p>Global variables can be registered in an extension via the <code class="docutils literal"><span class="pre">getGlobals()</span></code>
method:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Project_Twig_Extension</span> <span class="n">extends</span> <span class="n">Twig_Extension</span> <span class="n">implements</span> <span class="n">Twig_Extension_GlobalsInterface</span>
<span class="p">{</span>
<span class="n">public</span> <span class="n">function</span> <span class="n">getGlobals</span><span class="p">()</span>
<span class="p">{</span>
<span class="k">return</span> <span class="n">array</span><span class="p">(</span>
<span class="s1">'text'</span> <span class="o">=></span> <span class="n">new</span> <span class="n">Text</span><span class="p">(),</span>
<span class="p">);</span>
<span class="p">}</span>
<span class="o">//</span> <span class="o">...</span>
<span class="p">}</span>
</pre></div>
</div>
</div>
<div class="section" id="id2">
<h3>Functions<a class="headerlink" href="#id2" title="Permalink to this headline">¶</a></h3>
<p>Functions can be registered in an extension via the <code class="docutils literal"><span class="pre">getFunctions()</span></code>
method:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Project_Twig_Extension</span> <span class="n">extends</span> <span class="n">Twig_Extension</span>
<span class="p">{</span>
<span class="n">public</span> <span class="n">function</span> <span class="n">getFunctions</span><span class="p">()</span>
<span class="p">{</span>
<span class="k">return</span> <span class="n">array</span><span class="p">(</span>
<span class="n">new</span> <span class="n">Twig_Function</span><span class="p">(</span><span class="s1">'lipsum'</span><span class="p">,</span> <span class="s1">'generate_lipsum'</span><span class="p">),</span>
<span class="p">);</span>
<span class="p">}</span>
<span class="o">//</span> <span class="o">...</span>
<span class="p">}</span>
</pre></div>
</div>
</div>
<div class="section" id="id3">
<h3>Filters<a class="headerlink" href="#id3" title="Permalink to this headline">¶</a></h3>
<p>To add a filter to an extension, you need to override the <code class="docutils literal"><span class="pre">getFilters()</span></code>
method. This method must return an array of filters to add to the Twig
environment:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Project_Twig_Extension</span> <span class="n">extends</span> <span class="n">Twig_Extension</span>
<span class="p">{</span>
<span class="n">public</span> <span class="n">function</span> <span class="n">getFilters</span><span class="p">()</span>
<span class="p">{</span>
<span class="k">return</span> <span class="n">array</span><span class="p">(</span>
<span class="n">new</span> <span class="n">Twig_Filter</span><span class="p">(</span><span class="s1">'rot13'</span><span class="p">,</span> <span class="s1">'str_rot13'</span><span class="p">),</span>
<span class="p">);</span>
<span class="p">}</span>
<span class="o">//</span> <span class="o">...</span>
<span class="p">}</span>
</pre></div>
</div>
</div>
<div class="section" id="id4">
<h3>Tags<a class="headerlink" href="#id4" title="Permalink to this headline">¶</a></h3>
<p>Adding a tag in an extension can be done by overriding the
<code class="docutils literal"><span class="pre">getTokenParsers()</span></code> method. This method must return an array of tags to add
to the Twig environment:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Project_Twig_Extension</span> <span class="n">extends</span> <span class="n">Twig_Extension</span>
<span class="p">{</span>
<span class="n">public</span> <span class="n">function</span> <span class="n">getTokenParsers</span><span class="p">()</span>
<span class="p">{</span>
<span class="k">return</span> <span class="n">array</span><span class="p">(</span><span class="n">new</span> <span class="n">Project_Set_TokenParser</span><span class="p">());</span>
<span class="p">}</span>
<span class="o">//</span> <span class="o">...</span>
<span class="p">}</span>
</pre></div>
</div>
<p>In the above code, we have added a single new tag, defined by the
<code class="docutils literal"><span class="pre">Project_Set_TokenParser</span></code> class. The <code class="docutils literal"><span class="pre">Project_Set_TokenParser</span></code> class is
responsible for parsing the tag and compiling it to PHP.</p>
</div>
<div class="section" id="operators">
<h3>Operators<a class="headerlink" href="#operators" title="Permalink to this headline">¶</a></h3>
<p>The <code class="docutils literal"><span class="pre">getOperators()</span></code> methods lets you add new operators. Here is how to add
<code class="docutils literal"><span class="pre">!</span></code>, <code class="docutils literal"><span class="pre">||</span></code>, and <code class="docutils literal"><span class="pre">&&</span></code> operators:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Project_Twig_Extension</span> <span class="n">extends</span> <span class="n">Twig_Extension</span>
<span class="p">{</span>
<span class="n">public</span> <span class="n">function</span> <span class="n">getOperators</span><span class="p">()</span>
<span class="p">{</span>
<span class="k">return</span> <span class="n">array</span><span class="p">(</span>
<span class="n">array</span><span class="p">(</span>
<span class="s1">'!'</span> <span class="o">=></span> <span class="n">array</span><span class="p">(</span><span class="s1">'precedence'</span> <span class="o">=></span> <span class="mi">50</span><span class="p">,</span> <span class="s1">'class'</span> <span class="o">=></span> <span class="s1">'Twig_Node_Expression_Unary_Not'</span><span class="p">),</span>
<span class="p">),</span>
<span class="n">array</span><span class="p">(</span>
<span class="s1">'||'</span> <span class="o">=></span> <span class="n">array</span><span class="p">(</span><span class="s1">'precedence'</span> <span class="o">=></span> <span class="mi">10</span><span class="p">,</span> <span class="s1">'class'</span> <span class="o">=></span> <span class="s1">'Twig_Node_Expression_Binary_Or'</span><span class="p">,</span> <span class="s1">'associativity'</span> <span class="o">=></span> <span class="n">Twig_ExpressionParser</span><span class="p">::</span><span class="n">OPERATOR_LEFT</span><span class="p">),</span>
<span class="s1">'&&'</span> <span class="o">=></span> <span class="n">array</span><span class="p">(</span><span class="s1">'precedence'</span> <span class="o">=></span> <span class="mi">15</span><span class="p">,</span> <span class="s1">'class'</span> <span class="o">=></span> <span class="s1">'Twig_Node_Expression_Binary_And'</span><span class="p">,</span> <span class="s1">'associativity'</span> <span class="o">=></span> <span class="n">Twig_ExpressionParser</span><span class="p">::</span><span class="n">OPERATOR_LEFT</span><span class="p">),</span>
<span class="p">),</span>
<span class="p">);</span>
<span class="p">}</span>
<span class="o">//</span> <span class="o">...</span>
<span class="p">}</span>
</pre></div>
</div>
</div>
<div class="section" id="id5">
<h3>Tests<a class="headerlink" href="#id5" title="Permalink to this headline">¶</a></h3>
<p>The <code class="docutils literal"><span class="pre">getTests()</span></code> method lets you add new test functions:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Project_Twig_Extension</span> <span class="n">extends</span> <span class="n">Twig_Extension</span>
<span class="p">{</span>
<span class="n">public</span> <span class="n">function</span> <span class="n">getTests</span><span class="p">()</span>
<span class="p">{</span>
<span class="k">return</span> <span class="n">array</span><span class="p">(</span>
<span class="n">new</span> <span class="n">Twig_Test</span><span class="p">(</span><span class="s1">'even'</span><span class="p">,</span> <span class="s1">'twig_test_even'</span><span class="p">),</span>
<span class="p">);</span>
<span class="p">}</span>
<span class="o">//</span> <span class="o">...</span>
<span class="p">}</span>
</pre></div>
</div>
</div>
<div class="section" id="definition-vs-runtime">
<h3>Definition vs Runtime<a class="headerlink" href="#definition-vs-runtime" title="Permalink to this headline">¶</a></h3>
<p>Twig filters, functions, and tests runtime implementations can be defined as
any valid PHP callable:</p>
<ul class="simple">
<li><strong>functions/static methods</strong>: Simple to implement and fast (used by all Twig
core extensions); but it is hard for the runtime to depend on external
objects;</li>
<li><strong>closures</strong>: Simple to implement;</li>
<li><strong>object methods</strong>: More flexible and required if your runtime code depends
on external objects.</li>
</ul>
<p>The simplest way to use methods is to define them on the extension itself:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>class Project_Twig_Extension extends Twig_Extension
{
private $rot13Provider;
public function __construct($rot13Provider)
{
$this->rot13Provider = $rot13Provider;
}
public function getFunctions()
{
return array(
new Twig_Function('rot13', array($this, 'rot13')),
);
}
public function rot13($value)
{
return $this->rot13Provider->rot13($value);
}
}
</pre></div>
</div>
<p>This is very convenient but not recommended as it makes template compilation
depend on runtime dependencies even if they are not needed (think for instance
as a dependency that connects to a database engine).</p>
<p>You can easily decouple the extension definitions from their runtime
implementations by registering a <code class="docutils literal"><span class="pre">Twig_RuntimeLoaderInterface</span></code> instance on
the environment that knows how to instantiate such runtime classes (runtime
classes must be autoload-able):</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>class RuntimeLoader implements Twig_RuntimeLoaderInterface
{
public function load($class)
{
// implement the logic to create an instance of $class
// and inject its dependencies
// most of the time, it means using your dependency injection container
if ('Project_Twig_RuntimeExtension' === $class) {
return new $class(new Rot13Provider());
} else {
// ...
}
}
}
$twig->addRuntimeLoader(new RuntimeLoader());
</pre></div>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Twig comes with a PSR-11 compatible runtime loader
(<code class="docutils literal"><span class="pre">Twig_ContainerRuntimeLoader</span></code>).</p>
</div>
<p>It is now possible to move the runtime logic to a new
<code class="docutils literal"><span class="pre">Project_Twig_RuntimeExtension</span></code> class and use it directly in the extension:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>class Project_Twig_RuntimeExtension
{
private $rot13Provider;
public function __construct($rot13Provider)
{
$this->rot13Provider = $rot13Provider;
}
public function rot13($value)
{
return $this->rot13Provider->rot13($value);
}
}
class Project_Twig_Extension extends Twig_Extension
{
public function getFunctions()
{
return array(
new Twig_Function('rot13', array('Project_Twig_RuntimeExtension', 'rot13')),
// or
new Twig_Function('rot13', 'Project_Twig_RuntimeExtension::rot13'),
);
}
}
</pre></div>
</div>
</div>
</div>
<div class="section" id="overloading">
<h2>Overloading<a class="headerlink" href="#overloading" title="Permalink to this headline">¶</a></h2>
<p>To overload an already defined filter, test, operator, global variable, or
function, re-define it in an extension and register it <strong>as late as
possible</strong> (order matters):</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>class MyCoreExtension extends Twig_Extension
{
public function getFilters()
{
return array(
new Twig_Filter('date', array($this, 'dateFilter')),
);
}
public function dateFilter($timestamp, $format = 'F j, Y H:i')
{
// do something different from the built-in date filter
}
}
$twig = new Twig_Environment($loader);
$twig->addExtension(new MyCoreExtension());
</pre></div>
</div>
<p>Here, we have overloaded the built-in <code class="docutils literal"><span class="pre">date</span></code> filter with a custom one.</p>
<p>If you do the same on the <code class="docutils literal"><span class="pre">Twig_Environment</span></code> itself, beware that it takes
precedence over any other registered extensions:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span>$twig = new Twig_Environment($loader);
$twig->addFilter(new Twig_Filter('date', function ($timestamp, $format = 'F j, Y H:i') {
// do something different from the built-in date filter
}));
// the date filter will come from the above registration, not
// from the registered extension below
$twig->addExtension(new MyCoreExtension());
</pre></div>
</div>
<div class="admonition caution">
<p class="first admonition-title">Caution</p>
<p class="last">Note that overloading the built-in Twig elements is not recommended as it
might be confusing.</p>
</div>
</div>
<div class="section" id="testing-an-extension">
<h2>Testing an Extension<a class="headerlink" href="#testing-an-extension" title="Permalink to this headline">¶</a></h2>
<div class="section" id="functional-tests">
<h3>Functional Tests<a class="headerlink" href="#functional-tests" title="Permalink to this headline">¶</a></h3>
<p>You can create functional tests for extensions simply by creating the
following file structure in your test directory:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="n">Fixtures</span><span class="o">/</span>
<span class="n">filters</span><span class="o">/</span>
<span class="n">foo</span><span class="o">.</span><span class="n">test</span>
<span class="n">bar</span><span class="o">.</span><span class="n">test</span>
<span class="n">functions</span><span class="o">/</span>
<span class="n">foo</span><span class="o">.</span><span class="n">test</span>
<span class="n">bar</span><span class="o">.</span><span class="n">test</span>
<span class="n">tags</span><span class="o">/</span>
<span class="n">foo</span><span class="o">.</span><span class="n">test</span>
<span class="n">bar</span><span class="o">.</span><span class="n">test</span>
<span class="n">IntegrationTest</span><span class="o">.</span><span class="n">php</span>
</pre></div>
</div>
<p>The <code class="docutils literal"><span class="pre">IntegrationTest.php</span></code> file should look like this:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Project_Tests_IntegrationTest</span> <span class="n">extends</span> <span class="n">Twig_Test_IntegrationTestCase</span>
<span class="p">{</span>
<span class="n">public</span> <span class="n">function</span> <span class="n">getExtensions</span><span class="p">()</span>
<span class="p">{</span>
<span class="k">return</span> <span class="n">array</span><span class="p">(</span>
<span class="n">new</span> <span class="n">Project_Twig_Extension1</span><span class="p">(),</span>
<span class="n">new</span> <span class="n">Project_Twig_Extension2</span><span class="p">(),</span>
<span class="p">);</span>
<span class="p">}</span>
<span class="n">public</span> <span class="n">function</span> <span class="n">getFixturesDir</span><span class="p">()</span>
<span class="p">{</span>
<span class="k">return</span> <span class="n">dirname</span><span class="p">(</span><span class="n">__FILE__</span><span class="p">)</span><span class="o">.</span><span class="s1">'/Fixtures/'</span><span class="p">;</span>
<span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
<p>Fixtures examples can be found within the Twig repository
<a class="reference external" href="https://github.com/twigphp/Twig/tree/master/test/Twig/Tests/Fixtures">tests/Twig/Fixtures</a> directory.</p>
</div>
<div class="section" id="node-tests">
<h3>Node Tests<a class="headerlink" href="#node-tests" title="Permalink to this headline">¶</a></h3>
<p>Testing the node visitors can be complex, so extend your test cases from
<code class="docutils literal"><span class="pre">Twig_Test_NodeTestCase</span></code>. Examples can be found in the Twig repository
<a class="reference external" href="https://github.com/twigphp/Twig/tree/master/test/Twig/Tests/Node">tests/Twig/Node</a> directory.</p>
</div>
</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="#">Extending Twig</a><ul>
<li><a class="reference internal" href="#globals">Globals</a></li>
<li><a class="reference internal" href="#filters">Filters</a><ul>
<li><a class="reference internal" href="#environment-aware-filters">Environment-aware Filters</a></li>
<li><a class="reference internal" href="#context-aware-filters">Context-aware Filters</a></li>
<li><a class="reference internal" href="#automatic-escaping">Automatic Escaping</a></li>
<li><a class="reference internal" href="#variadic-filters">Variadic Filters</a></li>
<li><a class="reference internal" href="#dynamic-filters">Dynamic Filters</a></li>
<li><a class="reference internal" href="#deprecated-filters">Deprecated Filters</a></li>
</ul>
</li>
<li><a class="reference internal" href="#functions">Functions</a></li>
<li><a class="reference internal" href="#tests">Tests</a></li>
<li><a class="reference internal" href="#tags">Tags</a><ul>
<li><a class="reference internal" href="#registering-a-new-tag">Registering a new tag</a></li>
<li><a class="reference internal" href="#defining-a-token-parser">Defining a Token Parser</a></li>
<li><a class="reference internal" href="#defining-a-node">Defining a Node</a></li>
</ul>
</li>
<li><a class="reference internal" href="#creating-an-extension">Creating an Extension</a><ul>
<li><a class="reference internal" href="#id1">Globals</a></li>
<li><a class="reference internal" href="#id2">Functions</a></li>
<li><a class="reference internal" href="#id3">Filters</a></li>
<li><a class="reference internal" href="#id4">Tags</a></li>
<li><a class="reference internal" href="#operators">Operators</a></li>
<li><a class="reference internal" href="#id5">Tests</a></li>
<li><a class="reference internal" href="#definition-vs-runtime">Definition vs Runtime</a></li>
</ul>
</li>
<li><a class="reference internal" href="#overloading">Overloading</a></li>
<li><a class="reference internal" href="#testing-an-extension">Testing an Extension</a><ul>
<li><a class="reference internal" href="#functional-tests">Functional Tests</a></li>
<li><a class="reference internal" href="#node-tests">Node Tests</a></li>
</ul>
</li>
</ul>
</li>
</ul>
<h4>Previous topic</h4>
<p class="topless"><a href="api.html"
title="previous chapter">Twig for Developers</a></p>
<h4>Next topic</h4>
<p class="topless"><a href="internals.html"
title="next chapter">Twig Internals</a></p>
<div role="note" aria-label="source link">
<h3>This Page</h3>
<ul class="this-page-menu">
<li><a href="_sources/advanced.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="internals.html" title="Twig Internals"
>next</a> |</li>
<li class="right" >
<a href="api.html" title="Twig for Developers"
>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>
|