@@ -45,11 +45,11 @@ Create a class that extends ``AbstractExtension`` and fill in the logic::
4545 public function getFilters()
4646 {
4747 return array(
48- new TwigFilter('price', array($this, 'priceFilter ')),
48+ new TwigFilter('price', array($this, 'formatPrice ')),
4949 );
5050 }
5151
52- public function priceFilter ($number, $decimals = 0, $decPoint = '.', $thousandsSep = ',')
52+ public function formatPrice ($number, $decimals = 0, $decPoint = '.', $thousandsSep = ',')
5353 {
5454 $price = number_format($number, $decimals, $decPoint, $thousandsSep);
5555 $price = '$'.$price;
@@ -58,9 +58,33 @@ Create a class that extends ``AbstractExtension`` and fill in the logic::
5858 }
5959 }
6060
61+ If you want to create a function instead of a filter, define the ``getFunctions() ``
62+ method:
63+
64+ // src/Twig/AppExtension.php
65+ namespace App\T wig;
66+
67+ use Twig\E xtension\A bstractExtension;
68+ use Twig\T wigFunction;
69+
70+ class AppExtension extends AbstractExtension
71+ {
72+ public function getFunctions()
73+ {
74+ return array(
75+ new TwigFunction('area', array($this, 'calculateArea')),
76+ );
77+ }
78+
79+ public function calculateArea(int $width, int $length)
80+ {
81+ return $width * $length;
82+ }
83+ }
84+
6185.. tip ::
6286
63- Along with custom filters, you can also add custom ` functions `_ and register
87+ Along with custom filters and functions , you can also register
6488 `global variables `_.
6589
6690Register an Extension as a Service
0 commit comments