You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: cookbook/templating/twig_extension.rst
+54-36Lines changed: 54 additions & 36 deletions
Original file line number
Diff line number
Diff line change
@@ -2,12 +2,16 @@
2
2
single: Twig extensions
3
3
4
4
How to write a custom Twig extension
5
-
============================================
5
+
====================================
6
6
7
-
The main motivation for writing an extension is to move often used code into a reusable class like adding support for internationalization.
8
-
An extension can define tags, filters, tests, operators, global variables, functions, and node visitors.
7
+
The main motivation for writing an extension is to move often used code
8
+
into a reusable class like adding support for internationalization.
9
+
An extension can define tags, filters, tests, operators, global variables,
10
+
functions, and node visitors.
9
11
10
-
Creating an extension also makes for a better separation of code that is executed at compilation time and code needed at runtime. As such, it makes your code faster.
12
+
Creating an extension also makes for a better separation of code that is
13
+
executed at compilation time and code needed at runtime. As such, it makes
14
+
your code faster.
11
15
12
16
.. tip::
13
17
@@ -17,42 +21,42 @@ Create the extension class
17
21
--------------------------
18
22
19
23
To get your custom functionality you must first create a Twig Extension class.
20
-
As an example we will create a price filter to format a given number into price.
24
+
As an example we will create a price filter to format a given number into price::
21
25
22
-
.. code-block:: php
26
+
// src/Acme/DemoBundle/Twig/AcmeExtension.php
23
27
24
-
<?php
25
-
26
-
// src/Acme/DemoBundle/Twig/AcmeExtension.php
28
+
namespace Acme\DemoBundle\Twig;
27
29
28
-
namespace Acme\DemoBundle\Twig;
30
+
use Twig_Extension;
31
+
use Twig_Filter_Method;
32
+
use Twig_Function_Method;
29
33
30
-
use Twig_Extension;
31
-
use Twig_Filter_Method;
32
-
use Twig_Function_Method;
34
+
class AcmeExtension extends Twig_Extension
35
+
{
36
+
public function getFilters()
37
+
{
38
+
return array(
39
+
'price' => new Twig_Filter_Method($this, 'priceFilter'),
40
+
);
41
+
}
42
+
43
+
public function priceFilter($number, $decimals = 0, $decPoint = '.', $thousandsSep = ',')
0 commit comments