How to Write a custom Twig Extension
How to Write a custom Twig Extension¶
The main motivation for writing an extension is to move often used code into a reusable class like adding support for internationalization. An extension can define tags, filters, tests, operators, global variables, functions, and node visitors.
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.
Tip
Before writing your own extensions, have a look at the Twig official extension repository.
Create the Extension Class¶
Note
This article describes how to write a custom Twig extension as of Twig 1.12. If you are using an older version, please read Twig extensions documentation legacy.
To get your custom functionality you must first create a Twig Extension class. As an example you’ll create a price filter to format a given number into price:
// src/AppBundle/Twig/AppExtension.php
namespace AppBundle\Twig;
class AppExtension extends \Twig_Extension
{
public function getFilters()
{
return array(
new \Twig_SimpleFilter('price', array($this, 'priceFilter')),
);
}
public function priceFilter($number, $decimals = 0, $decPoint = '.', $thousandsSep = ',')
{
$price = number_format($number, $decimals, $decPoint, $thousandsSep);
$price = '$'.$price;
return $price;
}
public function getName()
{
return 'app_extension';
}
}
Tip
Along with custom filters, you can also add custom functions and register global variables.
Register an Extension as a Service¶
Now you must let the Service Container know about your newly created Twig Extension:
- YAML
1 2 3 4 5 6 7
# app/config/services.yml services: app.twig_extension: class: AppBundle\Twig\AppExtension public: false tags: - { name: twig.extension }
- XML
1 2 3 4 5 6 7 8
<!-- app/config/services.xml --> <services> <service id="app.twig_extension" class="AppBundle\Twig\AppExtension" public="false"> <tag name="twig.extension" /> </service> </services>
- PHP
1 2 3 4 5 6 7 8
// app/config/services.php use AppBundle\Twig\AppExtension; use Symfony\Component\DependencyInjection\Definition; $container ->register('app.twig_extension', AppExtension::class) ->setPublic(false) ->addTag('twig.extension');
Using the custom Extension¶
Using your newly created Twig Extension is no different than any other:
1 2 | {# outputs $5,500.00 #}
{{ '5500'|price }}
|
Passing other arguments to your filter:
1 2 | {# outputs $5500,2516 #}
{{ '5500.25155'|price(4, ',', '') }}
|
Learning further¶
For a more in-depth look into Twig Extensions, please take a look at the Twig extensions documentation.
This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.