本文共 2778 字,大约阅读时间需要 9 分钟。
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 . 在创建您自己的扩展之前,请先看一下 |
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扩展类。作为示例,我们将创建一个价格过滤器,用以将给定数字转成价格格式: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扩展: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 . 记住,Twig扩展并非被延迟加载。这就意味着如果您的服务(或本例中的Twig扩展)依赖request服务的话,您将有更高的几率得到CircularReferenceException 或 ScopeWideningInjectionException 异常。详情请参见. |
Using your newly created Twig Extension is no different than any other:
使用您新建的Twig扩展与其它的没什么不同:Passing other arguments to your filter:
发送其它参数到您的过滤器:For a more in-depth look into Twig Extensions, please take a look at the .
要更深入地了解Twig扩展,请查看。
转载地址:http://xcora.baihongyu.com/