Skip to content

Commit 32e3179

Browse files
ThomasLandauerjaviereguiluz
authored andcommitted
Update twig_extension.rst
1 parent 9d3fa4a commit 32e3179

File tree

1 file changed

+26
-3
lines changed

1 file changed

+26
-3
lines changed

templating/twig_extension.rst

Lines changed: 26 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -41,11 +41,11 @@ As an example you'll create a price filter to format a given number into price::
4141
public function getFilters()
4242
{
4343
return array(
44-
new TwigFilter('price', array($this, 'priceFilter')),
44+
new TwigFilter('price', array($this, 'formatPrice')),
4545
);
4646
}
4747

48-
public function priceFilter($number, $decimals = 0, $decPoint = '.', $thousandsSep = ',')
48+
public function formatPrice($number, $decimals = 0, $decPoint = '.', $thousandsSep = ',')
4949
{
5050
$price = number_format($number, $decimals, $decPoint, $thousandsSep);
5151
$price = '$'.$price;
@@ -62,9 +62,32 @@ As an example you'll create a price filter to format a given number into price::
6262
versions before 1.26, include this method which is omitted in the example
6363
above.
6464

65+
Here's how to create a custom **function**::
66+
67+
// src/AppBundle/Twig/AppExtension.php
68+
namespace AppBundle\Twig;
69+
70+
use Twig\Extension\AbstractExtension;
71+
use Twig\TwigFunction;
72+
73+
class AppExtension extends AbstractExtension
74+
{
75+
public function getFunctions()
76+
{
77+
return array(
78+
new TwigFunction('total', array($this, 'calculateArea')),
79+
);
80+
}
81+
82+
public function calculateArea(int $width, int $length)
83+
{
84+
return $width * $length;
85+
}
86+
}
87+
6588
.. tip::
6689

67-
Along with custom filters, you can also add custom `functions`_ and register
90+
Along with custom filters and functions, you can also register
6891
`global variables`_.
6992

7093
Register an Extension as a Service

0 commit comments

Comments
 (0)