diff --git a/templating/twig_extension.rst b/templating/twig_extension.rst index e9a58badd5d..e1b5350ab78 100644 --- a/templating/twig_extension.rst +++ b/templating/twig_extension.rst @@ -41,11 +41,11 @@ As an example you'll create a price filter to format a given number into price:: public function getFilters() { return array( - new TwigFilter('price', array($this, 'priceFilter')), + new TwigFilter('price', array($this, 'formatPrice')), ); } - public function priceFilter($number, $decimals = 0, $decPoint = '.', $thousandsSep = ',') + public function formatPrice($number, $decimals = 0, $decPoint = '.', $thousandsSep = ',') { $price = number_format($number, $decimals, $decPoint, $thousandsSep); $price = '$'.$price; @@ -62,9 +62,32 @@ As an example you'll create a price filter to format a given number into price:: versions before 1.26, include this method which is omitted in the example above. +Here's how to create a custom **function**:: + + // src/AppBundle/Twig/AppExtension.php + namespace AppBundle\Twig; + + use Twig\Extension\AbstractExtension; + use Twig\TwigFunction; + + class AppExtension extends AbstractExtension + { + public function getFunctions() + { + return array( + new TwigFunction('total', array($this, 'calculateArea')), + ); + } + + public function calculateArea(int $width, int $length) + { + return $width * $length; + } + } + .. tip:: - Along with custom filters, you can also add custom `functions`_ and register + Along with custom filters and functions, you can also register `global variables`_. Register an Extension as a Service