@@ -1555,7 +1555,9 @@ as currency:
1555
1555
1556
1556
.. _templates-twig-filter-attribute :
1557
1557
1558
- Create a class and fill in the logic::
1558
+ Create a class with a method that contains the filter logic, then add
1559
+ the `#[AsTwigFilter] ` attribute to define the name and options of
1560
+ the Twig filter::
1559
1561
1560
1562
// src/Twig/AppExtension.php
1561
1563
namespace App\Twig;
@@ -1577,7 +1579,7 @@ Create a class and fill in the logic::
1577
1579
.. _templates-twig-function-attribute :
1578
1580
1579
1581
If you want to create a function instead of a filter, use the
1580
- ``AsTwigFunction `` attribute::
1582
+ ``#[ AsTwigFunction] `` attribute::
1581
1583
1582
1584
// src/Twig/AppExtension.php
1583
1585
namespace App\Twig;
@@ -1601,7 +1603,8 @@ If you want to create a function instead of a filter, use the
1601
1603
.. versionadded :: 7.3
1602
1604
1603
1605
Support for the ``#[AsTwigFilter] `` and ``#[AsTwigFunction] `` attributes was introduced in Symfony 7.3.
1604
- Previously, you had to use the ``getFilters() `` and ``getFunctions() `` methods.
1606
+ Previously, you had to extend the `AbstractExtension ` class, and override the
1607
+ ``getFilters() `` and ``getFunctions() `` methods.
1605
1608
1606
1609
Register an Extension as a Service
1607
1610
..................................
@@ -1626,10 +1629,11 @@ this command to confirm that your new filter was successfully registered:
1626
1629
Creating Lazy-Loaded Twig Extensions
1627
1630
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1628
1631
1629
- Including the code of the custom filters/functions in the Twig extension class
1630
- is the simplest way to create extensions. However, Twig must initialize all
1631
- extensions before rendering any template, even if the template doesn't use an
1632
- extension. Note that if you use attributes, this part is not needed.
1632
+ When using attributes to extend Twig, the services are initialized only when
1633
+ the functions or filters are used to render the template. But in case you use the
1634
+ classic approach by extending the ``AbstractExtension `` class, Twig initialize all extensions before
1635
+ rendering rendering any template, even if the template doesn't use an
1636
+ extension.
1633
1637
1634
1638
If extensions don't define dependencies (i.e. if you don't inject services in
1635
1639
them) performance is not affected. However, if extensions define lots of complex
0 commit comments