Skip to content

Update twig_extension.rst #10593

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 3 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 26 additions & 3 deletions templating/twig_extension.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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
Expand Down