Browse code

tweaked the doc

Fabien Potencier authored on 27/04/2019 11:22:50
Showing 7 changed files
... ...
@@ -13,10 +13,10 @@ itself with node visitors.
13 13
 
14 14
 .. note::
15 15
 
16
-    The first section of this chapter describes how to extend Twig easily. If
17
-    you want to reuse your changes in different projects or if you want to
18
-    share them with others, you should then create an extension as described
19
-    in the following section.
16
+    The first section of this chapter describes how to extend Twig. If you want
17
+    to reuse your changes in different projects or if you want to share them
18
+    with others, you should then create an extension as described in the
19
+    following section.
20 20
 
21 21
 .. caution::
22 22
 
... ...
@@ -56,7 +56,7 @@ three main reasons:
56 56
       {{ 'some text' ~ {% lipsum 40 %} ~ 'some more text' }}
57 57
 
58 58
 In fact, you rarely need to create tags; and that's good news because tags are
59
-the most complex extension point of Twig.
59
+the most complex extension point.
60 60
 
61 61
 Now, let's use a ``lipsum`` *filter*:
62 62
 
... ...
@@ -64,10 +64,9 @@ Now, let's use a ``lipsum`` *filter*:
64 64
 
65 65
     {{ 40|lipsum }}
66 66
 
67
-Again, it works, but it looks weird. A filter transforms the passed value to
68
-something else but here we use the value to indicate the number of words to
69
-generate (so, ``40`` is an argument of the filter, not the value we want to
70
-transform).
67
+Again, it works. But a filter should transform the passed value to something
68
+else. Here, we use the value to indicate the number of words to generate (so,
69
+``40`` is an argument of the filter, not the value we want to transform).
71 70
 
72 71
 Next, let's use a ``lipsum`` *function*:
73 72
 
... ...
@@ -84,8 +83,8 @@ extension point to use. And you can use it anywhere an expression is accepted:
84 83
 
85 84
     {% set lipsum = lipsum(40) %}
86 85
 
87
-Last but not the least, you can also use a *global* object with a method able
88
-to generate lorem ipsum text:
86
+Lastly, you can also use a *global* object with a method able to generate lorem
87
+ipsum text:
89 88
 
90 89
 .. code-block:: twig
91 90
 
... ...
@@ -99,13 +98,13 @@ Keep in mind the following when you want to extend Twig:
99 98
 ========== ========================== ========== =========================
100 99
 What?      Implementation difficulty? How often? When?
101 100
 ========== ========================== ========== =========================
102
-*macro*    trivial                    frequent   Content generation
103
-*global*   trivial                    frequent   Helper object
104
-*function* trivial                    frequent   Content generation
105
-*filter*   trivial                    frequent   Value transformation
101
+*macro*    simple                     frequent   Content generation
102
+*global*   simple                     frequent   Helper object
103
+*function* simple                     frequent   Content generation
104
+*filter*   simple                     frequent   Value transformation
106 105
 *tag*      complex                    rare       DSL language construct
107
-*test*     trivial                    rare       Boolean decision
108
-*operator* trivial                    rare       Values transformation
106
+*test*     simple                     rare       Boolean decision
107
+*operator* simple                     rare       Values transformation
109 108
 ========== ========================== ========== =========================
110 109
 
111 110
 Globals
... ...
@@ -126,7 +125,7 @@ You can then use the ``text`` variable anywhere in a template:
126 125
 Filters
127 126
 -------
128 127
 
129
-Creating a filter is as simple as associating a name with a PHP callable::
128
+Creating a filter consists of associating a name with a PHP callable::
130 129
 
131 130
     // an anonymous function
132 131
     $filter = new \Twig\TwigFilter('rot13', function ($string) {
... ...
@@ -149,7 +148,7 @@ The first argument passed to the ``\Twig\TwigFilter`` constructor is the name
149 148
 of the filter you will use in templates and the second one is the PHP callable
150 149
 to associate with it.
151 150
 
152
-Then, add the filter to your Twig environment::
151
+Then, add the filter to the Twig environment::
153 152
 
154 153
     $twig = new \Twig\Environment($loader);
155 154
     $twig->addFilter($filter);
... ...
@@ -251,14 +250,14 @@ option array.
251 250
 Dynamic Filters
252 251
 ~~~~~~~~~~~~~~~
253 252
 
254
-A filter name containing the special ``*`` character is a dynamic filter as
255
-the ``*`` can be any string::
253
+A filter name containing the special ``*`` character is a dynamic filter and
254
+the ``*`` part will match any string::
256 255
 
257 256
     $filter = new \Twig\TwigFilter('*_path', function ($name, $arguments) {
258 257
         // ...
259 258
     });
260 259
 
261
-The following filters will be matched by the above defined dynamic filter:
260
+The following filters are matched by the above defined dynamic filter:
262 261
 
263 262
 * ``product_path``
264 263
 * ``category_path``
... ...
@@ -269,10 +268,10 @@ A dynamic filter can define more than one dynamic parts::
269 268
         // ...
270 269
     });
271 270
 
272
-The filter will receive all dynamic part values before the normal filter
273
-arguments, but after the environment and the context. For instance, a call to
274
-``'foo'|a_path_b()`` will result in the following arguments to be passed to
275
-the filter: ``('a', 'b', 'foo')``.
271
+The filter receives all dynamic part values before the normal filter arguments,
272
+but after the environment and the context. For instance, a call to
273
+``'foo'|a_path_b()`` will result in the following arguments to be passed to the
274
+filter: ``('a', 'b', 'foo')``.
276 275
 
277 276
 Deprecated Filters
278 277
 ~~~~~~~~~~~~~~~~~~
... ...
@@ -334,7 +333,7 @@ objects are 'red'::
334 333
     });
335 334
     $twig->addTest($test);
336 335
 
337
-Test functions should always return true/false.
336
+Test functions must always return ``true``/``false``.
338 337
 
339 338
 When creating tests you can use the ``node_class`` option to provide custom test
340 339
 compilation. This is useful if your test can be compiled into PHP primitives.
... ...
@@ -360,8 +359,8 @@ This is used by many of the tests built into Twig::
360 359
         }
361 360
     }
362 361
 
363
-The above example shows how you can create tests that use a node class. The
364
-node class has access to one sub-node called 'node'. This sub-node contains the
362
+The above example shows how you can create tests that use a node class. The node
363
+class has access to one sub-node called ``node``. This sub-node contains the
365 364
 value that is being tested. When the ``odd`` filter is used in code such as:
366 365
 
367 366
 .. code-block:: twig
... ...
@@ -377,7 +376,7 @@ various other arguments that have been provided to your test.
377 376
 
378 377
 If you want to pass a variable number of positional or named arguments to the
379 378
 test, set the ``is_variadic`` option to ``true``. Tests support dynamic
380
-names (see dynamic filters and functions for the syntax).
379
+names (see dynamic filters for the syntax).
381 380
 
382 381
 Tags
383 382
 ----
... ...
@@ -429,8 +428,8 @@ Most of the time though, a tag is not needed:
429 428
 
430 429
 If you still want to create a tag for a new language construct, great!
431 430
 
432
-Let's create a simple ``set`` tag that allows the definition of simple
433
-variables from within a template. The tag can be used like follows:
431
+Let's create a ``set`` tag that allows the definition of simple variables from
432
+within a template. The tag can be used like follows:
434 433
 
435 434
 .. code-block:: twig
436 435
 
... ...
@@ -444,8 +443,7 @@ variables from within a template. The tag can be used like follows:
444 443
 
445 444
     The ``set`` tag is part of the Core extension and as such is always
446 445
     available. The built-in version is slightly more powerful and supports
447
-    multiple assignments by default (cf. the template designers chapter for
448
-    more information).
446
+    multiple assignments by default.
449 447
 
450 448
 Three steps are needed to define a new tag:
451 449
 
... ...
@@ -458,8 +456,8 @@ Three steps are needed to define a new tag:
458 456
 Registering a new tag
459 457
 ~~~~~~~~~~~~~~~~~~~~~
460 458
 
461
-Adding a tag is as simple as calling the ``addTokenParser`` method on the
462
-``\Twig\Environment`` instance::
459
+Add a tag by calling the ``addTokenParser`` method on the ``\Twig\Environment``
460
+instance::
463 461
 
464 462
     $twig = new \Twig\Environment($loader);
465 463
     $twig->addTokenParser(new Project_Set_TokenParser());
... ...
@@ -524,7 +522,7 @@ the ``set`` tag.
524 522
 Defining a Node
525 523
 ~~~~~~~~~~~~~~~
526 524
 
527
-The ``Project_Set_Node`` class itself is rather simple::
525
+The ``Project_Set_Node`` class itself is quite short::
528 526
 
529 527
     class Project_Set_Node extends \Twig\Node\Node
530 528
     {
... ...
@@ -575,8 +573,7 @@ Creating an Extension
575 573
 
576 574
 The main motivation for writing an extension is to move often used code into a
577 575
 reusable class like adding support for internationalization. An extension can
578
-define tags, filters, tests, operators, global variables, functions, and node
579
-visitors.
576
+define tags, filters, tests, operators, functions, and node visitors.
580 577
 
581 578
 Most of the time, it is useful to create a single extension for your project,
582 579
 to host all the specific tags and filters you want to add to Twig.
... ...
@@ -674,16 +671,15 @@ empty implementations for all methods:
674 671
     {
675 672
     }
676 673
 
677
-Of course, this extension does nothing for now. We will customize it in the
678
-next sections.
674
+This extension does nothing for now. We will customize it in the next sections.
679 675
 
680 676
 .. note::
681 677
 
682 678
     Prior to Twig 1.26, you must implement the ``getName()`` method which must
683 679
     return a unique identifier for the extension.
684 680
 
685
-Twig does not care where you save your extension on the filesystem, as all
686
-extensions must be registered explicitly to be available in your templates.
681
+You can save your extension anywhere on the filesystem, as all extensions must
682
+be registered explicitly to be available in your templates.
687 683
 
688 684
 You can register an extension by using the ``addExtension()`` method on your
689 685
 main ``Environment`` object::
... ...
@@ -775,7 +771,7 @@ Operators
775 771
 ~~~~~~~~~
776 772
 
777 773
 The ``getOperators()`` methods lets you add new operators. Here is how to add
778
-``!``, ``||``, and ``&&`` operators::
774
+the ``!``, ``||``, and ``&&`` operators::
779 775
 
780 776
     class Project_Twig_Extension extends \Twig\Extension\AbstractExtension
781 777
     {
... ...
@@ -880,7 +876,7 @@ instance on the environment that knows how to instantiate such runtime classes
880 876
 .. note::
881 877
 
882 878
     As of Twig 1.32, Twig comes with a PSR-11 compatible runtime loader
883
-    (``\Twig\RuntimeLoader\ContainerRuntimeLoader``) that works on PHP 5.3+.
879
+    (``\Twig\RuntimeLoader\ContainerRuntimeLoader``).
884 880
 
885 881
 It is now possible to move the runtime logic to a new
886 882
 ``Project_Twig_RuntimeExtension`` class and use it directly in the extension::
... ...
@@ -961,8 +957,8 @@ Testing an Extension
961 957
 Functional Tests
962 958
 ~~~~~~~~~~~~~~~~
963 959
 
964
-You can create functional tests for extensions simply by creating the
965
-following file structure in your test directory::
960
+You can create functional tests for extensions by creating the following file
961
+structure in your test directory::
966 962
 
967 963
     Fixtures/
968 964
         filters/
... ...
@@ -10,16 +10,14 @@ Basics
10 10
 
11 11
 Twig uses a central object called the **environment** (of class
12 12
 ``\Twig\Environment``). Instances of this class are used to store the
13
-configuration and extensions, and are used to load templates from the file
14
-system or other locations.
13
+configuration and extensions, and are used to load templates.
15 14
 
16
-Most applications will create one ``\Twig\Environment`` object on application
17
-initialization and use that to load templates. In some cases it's however
18
-useful to have multiple environments side by side, if different configurations
19
-are in use.
15
+Most applications create one ``\Twig\Environment`` object on application
16
+initialization and use that to load templates. In some cases, it might be useful
17
+to have multiple environments side by side, with different configurations.
20 18
 
21
-The simplest way to configure Twig to load templates for your application
22
-looks roughly like this::
19
+The typical way to configure Twig to load templates for an application looks
20
+roughly like this::
23 21
 
24 22
     require_once '/path/to/lib/Twig/Autoloader.php';
25 23
     Twig_Autoloader::register();
... ...
@@ -29,8 +27,8 @@ looks roughly like this::
29 27
         'cache' => '/path/to/compilation_cache',
30 28
     ]);
31 29
 
32
-This will create a template environment with the default settings and a loader
33
-that looks up the templates in the ``/path/to/templates/`` folder. Different
30
+This creates a template environment with a default configuration and a loader
31
+that looks up templates in the ``/path/to/templates/`` directory. Different
34 32
 loaders are available and you can also write your own if you want to load
35 33
 templates from a database or other resources.
36 34
 
... ...
@@ -53,7 +51,7 @@ returns a ``\Twig\TemplateWrapper`` instance::
53 51
 
54 52
 .. note::
55 53
 
56
-    Before Twig 1.28, you should use ``loadTemplate()`` instead which returns a
54
+    Before Twig 1.28, use ``loadTemplate()`` instead which returns a
57 55
     ``\Twig\Template`` instance.
58 56
 
59 57
 To render the template with some variables, call the ``render()`` method::
... ...
@@ -62,7 +60,7 @@ To render the template with some variables, call the ``render()`` method::
62 60
 
63 61
 .. note::
64 62
 
65
-    The ``display()`` method is a shortcut to output the template directly.
63
+    The ``display()`` method is a shortcut to output the rendered template.
66 64
 
67 65
 You can also load and render the template in one fell swoop::
68 66
 
... ...
@@ -157,14 +155,14 @@ Compilation Cache
157 155
 
158 156
 All template loaders can cache the compiled templates on the filesystem for
159 157
 future reuse. It speeds up Twig a lot as templates are only compiled once; and
160
-the performance boost is even larger if you use a PHP accelerator such as APC.
161
-See the ``cache`` and ``auto_reload`` options of ``\Twig\Environment`` above
162
-for more information.
158
+the performance boost is even larger if you use a PHP accelerator such as
159
+OPCache. See the ``cache`` and ``auto_reload`` options of ``\Twig\Environment``
160
+above for more information.
163 161
 
164 162
 Built-in Loaders
165 163
 ~~~~~~~~~~~~~~~~
166 164
 
167
-Here is a list of the built-in loaders Twig provides:
165
+Here is a list of the built-in loaders:
168 166
 
169 167
 ``\Twig\Loader\FilesystemLoader``
170 168
 .................................
... ...
@@ -224,8 +222,8 @@ the directory might be different from the one used on production servers)::
224 222
 ``\Twig\Loader\ArrayLoader``
225 223
 ............................
226 224
 
227
-``\Twig\Loader\ArrayLoader`` loads a template from a PHP array. It's passed an array
228
-of strings bound to template names::
225
+``\Twig\Loader\ArrayLoader`` loads a template from a PHP array. It is passed an
226
+array of strings bound to template names::
229 227
 
230 228
     $loader = new \Twig\Loader\ArrayLoader([
231 229
         'index.html' => 'Hello {{ name }}!',
... ...
@@ -239,11 +237,11 @@ projects where storing all templates in a single PHP file might make sense.
239 237
 
240 238
 .. tip::
241 239
 
242
-    When using the ``Array`` or ``String`` loaders with a cache mechanism, you
243
-    should know that a new cache key is generated each time a template content
244
-    "changes" (the cache key being the source code of the template). If you
245
-    don't want to see your cache grows out of control, you need to take care
246
-    of clearing the old cache file by yourself.
240
+    When using the ``Array``loaders with a cache mechanism, you should know that
241
+    a new cache key is generated each time a template content "changes" (the
242
+    cache key being the source code of the template). If you don't want to see
243
+    your cache grows out of control, you need to take care of clearing the old
244
+    cache file by yourself.
247 245
 
248 246
 ``\Twig\Loader\ChainLoader``
249 247
 ............................
... ...
@@ -262,13 +260,10 @@ projects where storing all templates in a single PHP file might make sense.
262 260
 
263 261
     $twig = new \Twig\Environment($loader);
264 262
 
265
-When looking for a template, Twig will try each loader in turn and it will
266
-return as soon as the template is found. When rendering the ``index.html``
267
-template from the above example, Twig will load it with ``$loader2`` but the
268
-``base.html`` template will be loaded from ``$loader1``.
269
-
270
-``\Twig\Loader\ChainLoader`` accepts any loader that implements
271
-``\Twig\Loader\LoaderInterface``.
263
+When looking for a template, Twig tries each loader in turn and returns as soon
264
+as the template is found. When rendering the ``index.html`` template from the
265
+above example, Twig will load it with ``$loader2`` but the ``base.html``
266
+template will be loaded from ``$loader1``.
272 267
 
273 268
 .. note::
274 269
 
... ...
@@ -326,28 +321,34 @@ is still fresh, given the last modification time, or ``false`` otherwise.
326 321
 Using Extensions
327 322
 ----------------
328 323
 
329
-Twig extensions are packages that add new features to Twig. Using an
330
-extension is as simple as using the ``addExtension()`` method::
324
+Twig extensions are packages that add new features to Twig. Register an
325
+extension via the ``addExtension()`` method::
331 326
 
332 327
     $twig->addExtension(new \Twig\Extension\SandboxExtension());
333 328
 
334 329
 Twig comes bundled with the following extensions:
335 330
 
336
-* *Twig_Extension_Core*: Defines all the core features of Twig.
331
+* *Twig\Extension\CoreExtension*: Defines all the core features of Twig.
332
+
333
+* *Twig\Extension\DebugExtension*: Defines the ``dump`` function to help debug
334
+  template variables.
337 335
 
338
-* *Twig_Extension_Escaper*: Adds automatic output-escaping and the possibility
339
-  to escape/unescape blocks of code.
336
+* *Twig\Extension\EscaperExtension*: Adds automatic output-escaping and the
337
+  possibility to escape/unescape blocks of code.
340 338
 
341
-* *Twig_Extension_Sandbox*: Adds a sandbox mode to the default Twig
339
+* *Twig\Extension\SandboxExtension*: Adds a sandbox mode to the default Twig
342 340
   environment, making it safe to evaluate untrusted code.
343 341
 
344
-* *Twig_Extension_Profiler*: Enabled the built-in Twig profiler (as of Twig
345
-  1.18).
342
+* *Twig\Extension\ProfilerExtension*: Enabled the built-in Twig profiler (as of
343
+  Twig 1.18).
346 344
 
347
-* *Twig_Extension_Optimizer*: Optimizes the node tree before compilation.
345
+* *Twig\Extension\OptimizerExtension*: Optimizes the node tree before
346
+  compilation.
348 347
 
349
-The core, escaper, and optimizer extensions do not need to be added to the
350
-Twig environment, as they are registered by default.
348
+* *Twig\Extension\StringLoaderExtension*: Defined the ``template_from_string``
349
+   function to allow loading templates from string in a template.
350
+
351
+The Core, Escaper, and Optimizer extensions are registered by default.
351 352
 
352 353
 Built-in Extensions
353 354
 -------------------
... ...
@@ -537,7 +538,8 @@ compatible format::
537 538
     file_put_contents('/path/to/profile.prof', $dumper->dump($profile));
538 539
 
539 540
 Upload the profile to visualize it (create a `free account
540
-<https://blackfire.io/signup>`_ first):
541
+<https://blackfire.io/signup?utm_source=twig&utm_medium=doc&utm_campaign=profiler>`_
542
+first):
541 543
 
542 544
 .. code-block:: sh
543 545
 
... ...
@@ -561,13 +563,17 @@ Twig supports the following optimizations:
561 563
 
562 564
 * ``\Twig\NodeVisitor\OptimizerNodeVisitor::OPTIMIZE_ALL``, enables all optimizations
563 565
   (this is the default value).
566
+
564 567
 * ``\Twig\NodeVisitor\OptimizerNodeVisitor::OPTIMIZE_NONE``, disables all optimizations.
565 568
   This reduces the compilation time, but it can increase the execution time
566 569
   and the consumed memory.
570
+
567 571
 * ``\Twig\NodeVisitor\OptimizerNodeVisitor::OPTIMIZE_FOR``, optimizes the ``for`` tag by
568 572
   removing the ``loop`` variable creation whenever possible.
573
+
569 574
 * ``\Twig\NodeVisitor\OptimizerNodeVisitor::OPTIMIZE_RAW_FILTER``, removes the ``raw``
570 575
   filter whenever possible.
576
+
571 577
 * ``\Twig\NodeVisitor\OptimizerNodeVisitor::OPTIMIZE_VAR_ACCESS``, simplifies the creation
572 578
   and access of variables in the compiled templates whenever possible.
573 579
 
... ...
@@ -6,42 +6,11 @@ You have multiple ways to install Twig.
6 6
 Installing the Twig PHP package
7 7
 -------------------------------
8 8
 
9
-Installing via Composer (recommended)
10
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
11
-
12
-Install `Composer`_ and run the following command to get the latest version:
13
-
14
-.. code-block:: bash
15
-
16
-    composer require twig/twig:~1.0
17
-
18
-Installing from the tarball release
19
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
20
-
21
-1. Download the most recent tarball from the `download page`_
22
-2. Verify the integrity of the tarball http://fabien.potencier.org/article/73/signing-project-releases
23
-3. Unpack the tarball
24
-4. Move the files somewhere in your project
25
-
26
-Installing the development version
27
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
28
-
29
-.. code-block:: bash
30
-
31
-    git clone git://github.com/twigphp/Twig.git
32
-
33
-Installing the PEAR package
34
-~~~~~~~~~~~~~~~~~~~~~~~~~~~
35
-
36
-.. note::
37
-
38
-    Using PEAR for installing Twig is deprecated and Twig 1.15.1 was the last
39
-    version published on the PEAR channel; use Composer instead.
9
+Install `Composer`_ and run the following command:
40 10
 
41 11
 .. code-block:: bash
42 12
 
43
-    pear channel-discover pear.twig-project.org
44
-    pear install twig/Twig
13
+    composer require "twig/twig:^1.0"
45 14
 
46 15
 Installing the C extension
47 16
 --------------------------
... ...
@@ -49,16 +18,16 @@ Installing the C extension
49 18
 .. versionadded:: 1.4
50 19
     The C extension was added in Twig 1.4.
51 20
 
52
-.. note::
21
+Twig comes with an **optional** C extension that improves the performance of the
22
+Twig runtime engine.
23
+
24
+Note that this extension does not replace the PHP code but only provides an
25
+optimized version of the ``\Twig\Template::getAttribute()`` method; you must
26
+still install the regular PHP code
53 27
 
54
-    The C extension is **optional** but it brings some nice performance
55
-    improvements. Note that the extension is not a replacement for the PHP
56
-    code; it only implements a small part of the PHP code to improve the
57
-    performance at runtime; you must still install the regular PHP code.
58
-    The C extension is only compatible and useful for **PHP5**.
28
+The C extension is only compatible and useful for **PHP5**.
59 29
 
60
-Twig comes with a C extension that enhances the performance of the Twig
61
-runtime engine; install it like any other PHP extensions:
30
+Install it like any other PHP extensions:
62 31
 
63 32
 .. code-block:: bash
64 33
 
... ...
@@ -68,17 +37,6 @@ runtime engine; install it like any other PHP extensions:
68 37
     make
69 38
     make install
70 39
 
71
-.. note::
72
-
73
-    You can also install the C extension via PEAR (note that this method is
74
-    deprecated and newer versions of Twig are not available on the PEAR
75
-    channel):
76
-
77
-    .. code-block:: bash
78
-
79
-        pear channel-discover pear.twig-project.org
80
-        pear install twig/CTwig
81
-
82 40
 For Windows:
83 41
 
84 42
 1. Setup the build environment following the `PHP documentation`_
... ...
@@ -103,13 +61,11 @@ Finally, enable the extension in your ``php.ini`` configuration file:
103 61
 
104 62
 .. code-block:: ini
105 63
 
106
-    extension=twig.so #For Unix systems
107
-    extension=php_twig.dll #For Windows systems
64
+    extension=twig.so # For Unix systems
65
+    extension=php_twig.dll # For Windows systems
108 66
 
109 67
 And from now on, Twig will automatically compile your templates to take
110
-advantage of the C extension. Note that this extension does not replace the
111
-PHP code but only provides an optimized version of the
112
-``\Twig\Template::getAttribute()`` method.
68
+advantage of the C extension.
113 69
 
114 70
 .. _`download page`:     https://github.com/twigphp/Twig/tags
115 71
 .. _`Composer`:          https://getcomposer.org/download/
... ...
@@ -16,11 +16,13 @@ The rendering of a Twig template can be summarized into four key steps:
16 16
 
17 17
   * First, the **lexer** tokenizes the template source code into small pieces
18 18
     for easier processing;
19
+
19 20
   * Then, the **parser** converts the token stream into a meaningful tree
20 21
     of nodes (the Abstract Syntax Tree);
21
-  * Eventually, the *compiler* transforms the AST into PHP code.
22 22
 
23
-* **Evaluate** the template: It basically means calling the ``display()``
23
+  * Finally, the *compiler* transforms the AST into PHP code.
24
+
25
+* **Evaluate** the template: It means calling the ``display()``
24 26
   method of the compiled template and passing it the context.
25 27
 
26 28
 The Lexer
... ...
@@ -1,13 +1,11 @@
1 1
 Introduction
2 2
 ============
3 3
 
4
-This is the documentation for Twig, the flexible, fast, and secure template
4
+Welcome to the documentation for Twig, the flexible, fast, and secure template
5 5
 engine for PHP.
6 6
 
7
-If you have any exposure to other text-based template languages, such as
8
-Smarty, Django, or Jinja, you should feel right at home with Twig. It's both
9
-designer and developer friendly by sticking to PHP's principles and adding
10
-functionality useful for templating environments.
7
+Twig is both designer and developer friendly by sticking to PHP's principles and
8
+adding functionality useful for templating environments.
11 9
 
12 10
 The key-features are...
13 11
 
... ...
@@ -22,14 +20,13 @@ The key-features are...
22 20
   developer to define their own custom tags and filters, and to create their own DSL.
23 21
 
24 22
 Twig is used by many Open-Source projects like Symfony, Drupal8, eZPublish,
25
-phpBB, Piwik, OroCRM; and many frameworks have support for it as well like
26
-Slim, Yii, Laravel, Codeigniter and Kohana — just to name a few.
23
+phpBB, Matomo, OroCRM; and many frameworks have support for it as well like
24
+Slim, Yii, Laravel, and Codeigniter — just to name a few.
27 25
 
28 26
 Prerequisites
29 27
 -------------
30 28
 
31
-Twig needs at least **PHP 5.2.7** to run. As of 1.34, the minimum requirement
32
-was bumped to **PHP 5.3.3**.
29
+Twig needs at least **PHP 5.4.0** to run.
33 30
 
34 31
 Installation
35 32
 ------------
... ...
@@ -38,7 +35,7 @@ The recommended way to install Twig is via Composer:
38 35
 
39 36
 .. code-block:: bash
40 37
 
41
-    composer require "twig/twig:~1.0"
38
+    composer require "twig/twig:^1.0"
42 39
 
43 40
 .. note::
44 41
 
... ...
@@ -63,7 +60,7 @@ This section gives you a brief introduction to the PHP API for Twig.
63 60
     echo $twig->render('index', ['name' => 'Fabien']);
64 61
 
65 62
 Twig uses a loader (``\Twig\Loader\ArrayLoader``) to locate templates, and an
66
-environment (``\Twig\Environment``) to store the configuration.
63
+environment (``\Twig\Environment``) to store its configuration.
67 64
 
68 65
 The ``render()`` method loads the template passed as a first argument and
69 66
 renders it with the variables passed as a second argument.
... ...
@@ -77,10 +74,3 @@ filesystem loader::
77 74
     ]);
78 75
 
79 76
     echo $twig->render('index.html', ['name' => 'Fabien']);
80
-
81
-.. tip::
82
-
83
-    If you are not using Composer, use the Twig built-in autoloader::
84
-
85
-        require_once '/path/to/lib/Twig/Autoloader.php';
86
-        Twig_Autoloader::register();
... ...
@@ -13,8 +13,8 @@ Deprecated features generate deprecation notices (via a call to the
13 13
 ``trigger_error()`` PHP function). By default, they are silenced and never
14 14
 displayed nor logged.
15 15
 
16
-To easily remove all deprecated feature usages from your templates, write and
17
-run a script along the lines of the following::
16
+To remove all deprecated feature usages from your templates, write and run a
17
+script along the lines of the following::
18 18
 
19 19
     require_once __DIR__.'/vendor/autoload.php';
20 20
 
... ...
@@ -57,7 +57,7 @@ they won't be generated when templates are already cached.
57 57
     If you want to manage the deprecation notices from your PHPUnit tests, have
58 58
     a look at the `symfony/phpunit-bridge
59 59
     <https://github.com/symfony/phpunit-bridge>`_ package, which eases the
60
-    process a lot.
60
+    process.
61 61
 
62 62
 Making a Layout conditional
63 63
 ---------------------------
... ...
@@ -155,7 +155,7 @@ parent's full, unambiguous template path in the extends tag:
155 155
 Customizing the Syntax
156 156
 ----------------------
157 157
 
158
-Twig allows some syntax customization for the block delimiters. It's not
158
+Twig allows some syntax customization for the block delimiters. It's **not**
159 159
 recommended to use this feature as templates will be tied with your custom
160 160
 syntax. But for specific projects, it can make sense to change the defaults.
161 161
 
... ...
@@ -202,7 +202,7 @@ When Twig encounters a variable like ``article.title``, it tries to find a
202 202
 ``title`` public property in the ``article`` object.
203 203
 
204 204
 It also works if the property does not exist but is rather defined dynamically
205
-thanks to the magic ``__get()`` method; you just need to also implement the
205
+thanks to the magic ``__get()`` method; you need to also implement the
206 206
 ``__isset()`` magic method like shown in the following snippet of code::
207 207
 
208 208
     class Article
... ...
@@ -7,13 +7,13 @@ will be most useful as reference to those creating Twig templates.
7 7
 Synopsis
8 8
 --------
9 9
 
10
-A template is simply a text file. It can generate any text-based format (HTML,
10
+A template is a regular text file. It can generate any text-based format (HTML,
11 11
 XML, CSV, LaTeX, etc.). It doesn't have a specific extension, ``.html`` or
12 12
 ``.xml`` are just fine.
13 13
 
14 14
 A template contains **variables** or **expressions**, which get replaced with
15
-values when the template is evaluated, and **tags**, which control the logic
16
-of the template.
15
+values when the template is evaluated, and **tags**, which control the
16
+template's logic.
17 17
 
18 18
 Below is a minimal template that illustrates a few basics. We will cover further
19 19
 details later on:
... ...
@@ -38,8 +38,8 @@ details later on:
38 38
     </html>
39 39
 
40 40
 There are two kinds of delimiters: ``{% ... %}`` and ``{{ ... }}``. The first
41
-one is used to execute statements such as for-loops, the latter prints the
42
-result of an expression to the template.
41
+one is used to execute statements such as for-loops, the latter outputs the
42
+result of an expression.
43 43
 
44 44
 IDEs Integration
45 45
 ----------------
... ...
@@ -68,27 +68,16 @@ Variables
68 68
 ---------
69 69
 
70 70
 The application passes variables to the templates for manipulation in the
71
-template. Variables may have attributes or elements you can access,
72
-too. The visual representation of a variable depends heavily on the application providing
71
+template. Variables may have attributes or elements you can access, too. The
72
+visual representation of a variable depends heavily on the application providing
73 73
 it.
74 74
 
75
-You can use a dot (``.``) to access attributes of a variable (methods or
76
-properties of a PHP object, or items of a PHP array), or the so-called
77
-"subscript" syntax (``[]``):
75
+Use a dot (``.``) to access attributes of a variable (methods or properties of a
76
+PHP object, or items of a PHP array):
78 77
 
79 78
 .. code-block:: twig
80 79
 
81 80
     {{ foo.bar }}
82
-    {{ foo['bar'] }}
83
-
84
-When the attribute contains special characters (like ``-`` that would be
85
-interpreted as the minus operator), use the ``attribute`` function instead to
86
-access the variable attribute:
87
-
88
-.. code-block:: twig
89
-
90
-    {# equivalent to the non-working foo.data-foo #}
91
-    {{ attribute(foo, 'data-foo') }}
92 81
 
93 82
 .. note::
94 83
 
... ...
@@ -96,10 +85,6 @@ access the variable attribute:
96 85
     variable but the print statement. When accessing variables inside tags,
97 86
     don't put the braces around them.
98 87
 
99
-If a variable or attribute does not exist, you will receive a ``null`` value
100
-when the ``strict_variables`` option is set to ``false``; alternatively, if ``strict_variables``
101
-is set, Twig will throw an error (see :ref:`environment options<environment_options>`).
102
-
103 88
 .. sidebar:: Implementation
104 89
 
105 90
     For convenience's sake ``foo.bar`` does the following things on the PHP
... ...
@@ -113,16 +98,30 @@ is set, Twig will throw an error (see :ref:`environment options<environment_opti
113 98
     * if not, and if ``foo`` is an object, check that ``isBar`` is a valid method;
114 99
     * if not, return a ``null`` value.
115 100
 
116
-    ``foo['bar']`` on the other hand only works with PHP arrays:
101
+    Twig also supports a specific syntax for accessing items on PHP arrays,
102
+    ``foo['bar']``:
117 103
 
118 104
     * check if ``foo`` is an array and ``bar`` a valid element;
119 105
     * if not, return a ``null`` value.
120 106
 
107
+If a variable or attribute does not exist, you will receive a ``null`` value
108
+when the ``strict_variables`` option is set to ``false``; alternatively, if ``strict_variables``
109
+is set, Twig will throw an error (see :ref:`environment options<environment_options>`).
110
+
121 111
 .. note::
122 112
 
123 113
     If you want to access a dynamic attribute of a variable, use the
124 114
     :doc:`attribute<functions/attribute>` function instead.
125 115
 
116
+    The ``attribute`` function is also useful when the attribute contains
117
+    special characters (like ``-`` that would be interpreted as the minus
118
+    operator):
119
+
120
+    .. code-block:: twig
121
+
122
+        {# equivalent to the non-working foo.data-foo #}
123
+        {{ attribute(foo, 'data-foo') }}
124
+
126 125
 Global Variables
127 126
 ~~~~~~~~~~~~~~~~
128 127
 
... ...
@@ -148,9 +147,8 @@ Filters
148 147
 -------
149 148
 
150 149
 Variables can be modified by **filters**. Filters are separated from the
151
-variable by a pipe symbol (``|``) and may have optional arguments in
152
-parentheses. Multiple filters can be chained. The output of one filter is
153
-applied to the next.
150
+variable by a pipe symbol (``|``). Multiple filters can be chained. The output
151
+of one filter is applied to the next.
154 152
 
155 153
 The following example removes all HTML tags from the ``name`` and title-cases
156 154
 it:
... ...
@@ -160,13 +158,13 @@ it:
160 158
     {{ name|striptags|title }}
161 159
 
162 160
 Filters that accept arguments have parentheses around the arguments. This
163
-example will join a list by commas:
161
+example joins the elements of a list by commas:
164 162
 
165 163
 .. code-block:: twig
166 164
 
167 165
     {{ list|join(', ') }}
168 166
 
169
-To apply a filter on a section of code, wrap it in the
167
+To apply a filter on a section of code, wrap it with the
170 168
 :doc:`apply<tags/apply>` tag:
171 169
 
172 170
 .. code-block:: twig
... ...
@@ -338,11 +336,10 @@ allows you to build a base "skeleton" template that contains all the common
338 336
 elements of your site and defines **blocks** that child templates can
339 337
 override.
340 338
 
341
-Sounds complicated but it is very basic. It's easier to understand it by
342
-starting with an example.
339
+It's easier to understand the concept by starting with an example.
343 340
 
344
-Let's define a base template, ``base.html``, which defines a simple HTML
345
-skeleton document that you might use for a simple two-column page:
341
+Let's define a base template, ``base.html``, which defines an HTML skeleton
342
+document that might be used for a two-column page:
346 343
 
347 344
 .. code-block:: html+twig
348 345
 
... ...
@@ -417,9 +414,8 @@ parent block:
417 414
 
418 415
 .. note::
419 416
 
420
-    Twig also supports multiple inheritance with the so called horizontal reuse
421
-    with the help of the :doc:`use<tags/use>` tag. This is an advanced feature
422
-    hardly ever needed in regular templates.
417
+    Twig also supports multiple inheritance via "horizontal reuse" with the help
418
+    of the :doc:`use<tags/use>` tag.
423 419
 
424 420
 HTML Escaping
425 421
 -------------
... ...
@@ -437,19 +433,17 @@ The automatic escaping strategy can be configured via the
437 433
 Working with Manual Escaping
438 434
 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
439 435
 
440
-If manual escaping is enabled, it is **your** responsibility to escape
441
-variables if needed. What to escape? Any variable you don't trust.
436
+If manual escaping is enabled, it is **your** responsibility to escape variables
437
+if needed. What to escape? Any variable that comes from an untrusted source.
442 438
 
443
-Escaping works by piping the variable through the
444
-:doc:`escape<filters/escape>` or ``e`` filter:
439
+Escaping works by using the :doc:`escape<filters/escape>` or ``e`` filter:
445 440
 
446 441
 .. code-block:: twig
447 442
 
448 443
     {{ user.username|e }}
449 444
 
450 445
 By default, the ``escape`` filter uses the ``html`` strategy, but depending on
451
-the escaping context, you might want to explicitly use any other available
452
-strategies:
446
+the escaping context, you might want to explicitly use an other strategy:
453 447
 
454 448
 .. code-block:: twig
455 449
 
... ...
@@ -557,8 +551,7 @@ special ``varargs`` variable as a list of values.
557 551
 Expressions
558 552
 -----------
559 553
 
560
-Twig allows expressions everywhere. These work very similar to regular PHP and
561
-even if you're not working with PHP you should feel comfortable with it.
554
+Twig allows expressions everywhere.
562 555
 
563 556
 .. note::
564 557
 
... ...
@@ -597,7 +590,7 @@ exist:
597 590
   backslash (e.g. ``'c:\Program Files'``) escape it by doubling it
598 591
   (e.g. ``'c:\\Program Files'``).
599 592
 
600
-* ``42`` / ``42.23``: Integers and floating point numbers are created by just
593
+* ``42`` / ``42.23``: Integers and floating point numbers are created by
601 594
   writing the number down. If a dot is present the number is a float,
602 595
   otherwise an integer.
603 596
 
... ...
@@ -637,15 +630,15 @@ Arrays and hashes can be nested:
637 630
 .. tip::
638 631
 
639 632
     Using double-quoted or single-quoted strings has no impact on performance
640
-    but string interpolation is only supported in double-quoted strings.
633
+    but :ref:`string interpolation <templates-string-interpolation>` is only
634
+    supported in double-quoted strings.
641 635
 
642 636
 Math
643 637
 ~~~~
644 638
 
645
-Twig allows you to calculate with values. This is rarely useful in templates
646
-but exists for completeness' sake. The following operators are supported:
639
+Twig allows you to do math in templates; the following operators are supported:
647 640
 
648
-* ``+``: Adds two objects together (the operands are casted to numbers). ``{{
641
+* ``+``: Adds two numbers together (the operands are casted to numbers). ``{{
649 642
   1 + 1 }}`` is ``2``.
650 643
 
651 644
 * ``-``: Subtracts the second number from the first one. ``{{ 3 - 2 }}`` is
... ...
@@ -720,9 +713,8 @@ string:
720 713
 Containment Operator
721 714
 ~~~~~~~~~~~~~~~~~~~~
722 715
 
723
-The ``in`` operator performs containment test.
724
-
725
-It returns ``true`` if the left operand is contained in the right:
716
+The ``in`` operator performs containment test. It returns ``true`` if the left
717
+operand is contained in the right:
726 718
 
727 719
 .. code-block:: twig
728 720
 
... ...
@@ -787,7 +779,7 @@ The following operators don't fit into any of the other categories:
787 779
 * ``|``: Applies a filter.
788 780
 
789 781
 * ``..``: Creates a sequence based on the operand before and after the operator
790
-  (this is just syntactic sugar for the :doc:`range<functions/range>` function):
782
+  (this is syntactic sugar for the :doc:`range<functions/range>` function):
791 783
 
792 784
   .. code-block:: twig
793 785
 
... ...
@@ -807,7 +799,7 @@ The following operators don't fit into any of the other categories:
807 799
   " ~ name ~ "!" }}`` would return (assuming ``name`` is ``'John'``) ``Hello
808 800
   John!``.
809 801
 
810
-* ``.``, ``[]``: Gets an attribute of an object.
802
+* ``.``, ``[]``: Gets an attribute of a variable.
811 803
 
812 804
 * ``?:``: The ternary operator:
813 805
 
... ...
@@ -826,6 +818,8 @@ The following operators don't fit into any of the other categories:
826 818
       {# returns the value of foo if it is defined and not null, 'no' otherwise #}
827 819
       {{ foo ?? 'no' }}
828 820
 
821
+.. _templates-string-interpolation
822
+
829 823
 String Interpolation
830 824
 ~~~~~~~~~~~~~~~~~~~~
831 825
 
... ...
@@ -916,10 +910,8 @@ the modifiers on one side of a tag or on both sides:
916 910
 Extensions
917 911
 ----------
918 912
 
919
-Twig can be easily extended.
920
-
921
-If you are looking for new tags, filters, or functions, have a look at the Twig official
922
-`extension repository`_.
913
+Twig can be extended. If you are looking for new tags, filters, or functions,
914
+have a look at the Twig official `extension repository`_.
923 915
 
924 916
 If you want to create your own, read the :ref:`Creating an
925 917
 Extension<creating_extensions>` chapter.