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.
创建扩展还可以有效地分隔编译时和运行时代码。这样它可以让您的代码运行地更快。
Before writing your own extensions, have a look at the Twig official extension repository. 在创建您自己的扩展之前,请先看一下Twig官方扩展库 |
To get your custom functionality you must first create a Twig Extension class. As an example we will create a price filter to format a given number into price:
要实现定制功能,您首先必须创建一个Twig扩展类。作为示例,我们将创建一个价格过滤器,用以将给定数字转成价格格式:
- // src/Acme/DemoBundle/Twig/AcmeExtension.php
- namespace Acme\DemoBundle\Twig;
- use Twig_Extension;
- use Twig_Filter_Method;
- class AcmeExtension extends Twig_Extension
- {
- public function getFilters()
- {
- return array(
- 'price' => new Twig_Filter_Method($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 'acme_extension';
- }
- }
Along with custom filters, you can also add custom functions and register global variables. 除了定制过滤器,您还可以添加定制函数和注册全局变量。 |
Now you must let Service Container know about your newly created Twig Extension:
现在您必须让服务容器知道您新建的Twig扩展:
- <!-- src/Acme/DemoBundle/Resources/config/services.xml -->
- <services>
- <service id="acme.twig.acme_extension" class="Acme\DemoBundle\Twig\AcmeExtension">
- <tag name="twig.extension" />
- </service>
- </services>
Keep in mind that Twig Extensions are not lazily loaded. This means that there's a higher chance that you'll get a CircularReferenceException or a ScopeWideningInjectionException if any services (or your Twig Extension in this case) are dependent on the request service. For more information take a look at How to work with Scopes. 记住,Twig扩展并非被延迟加载。这就意味着如果您的服务(或本例中的Twig扩展)依赖request服务的话,您将有更高的几率得到CircularReferenceException 或 ScopeWideningInjectionException 异常。详情请参见如何使用范围. |
Using your newly created Twig Extension is no different than any other:
使用您新建的Twig扩展与其它的没什么不同:
- {# outputs $5,500.00 #}
- {{ '5500'|price }}
Passing other arguments to your filter:
发送其它参数到您的过滤器:
- {# outputs $5500,2516 #}
- {{ '5500.25155'|price(4, ',', '') }}
For a more in-depth look into Twig Extensions, please take a look at the Twig extensions documentation.
要更深入地了解Twig扩展,请查看Twig扩展文档。