Symfony3.4 如何自定义编写Twig扩展
创建扩展类
1、创建过滤器
例子:假设你要创建一个名为price将数字格式化为货币的过滤器
//twig模板中调用
{{ product.price|price }}
{{ product.price|price(2,',','.')}}
创建一个扩展AbstractExtension和填充逻辑的类:
// src/AppBundle/Twig/AppExtension.php
namespace AppBundle\Twig;
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;
class AppExtension extends AbstractExtension
{
public function getFilters()
{
return [
new TwigFilter('price', [$this, 'formatPrice']),
];
}
public function formatPrice($number, $decimals = 0, $decPoint = '.', $thousandsSep = ',')
{
$price = number_format($number, $decimals, $decPoint, $thousandsSep);
$price = '$'.$price;
return $price;
}
}
注意:在 Twig 1.26 之前,您的扩展必须定义一个额外的getName() 方法,该方法返回一个带有扩展内部名称的字符串(例如 app.my_extension)。当你的扩展需要兼容 1.26 之前的 Twig 版本时,包含上面示例中省略的这个方法。
创建自定义函数的方法:
// src/AppBundle/Twig/AppExtension.php
namespace AppBundle\Twig;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;
class AppExtension extends AbstractExtension
{
public function getFunctions()
{
return [
new TwigFunction('area', [$this, 'calculateArea']),
];
}
public function calculateArea(int $width, int $length)
{
return $width * $length;
}
}
将扩展注册为服务
接下来,将类注册为服务并使用 标记它twig.extension。
文件:app\config\services.yml
services:
AppBundle\Twig\AppExtension:
tags: [ twig.extension ]
现在可以在任何 Twig 模板中使用您的过滤器。
创建Twig扩展延迟加载
// src/AppBundle/Twig/AppExtension.php
namespace AppBundle\Twig;
use AppBundle\Twig\AppRuntime;
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;
class AppExtension extends AbstractExtension
{
public function getFilters()
{
return [
// the logic of this filter is now implemented in a different class
new TwigFilter('price', [AppRuntime::class, 'formatPrice']),
];
}
}
创建AppRuntime类,类中包含上一个formatPrice()方法的逻辑:
// src/AppBundle/Twig/AppRuntime.php
namespace AppBundle\Twig;
use Twig\Extension\RuntimeExtensionInterface;
class AppRuntime implements RuntimeExtensionInterface
{
public function __construct()
{
// this simple example doesn't define any dependency, but in your own
// extensions, you'll need to inject services using this constructor
}
public function formatPrice($number, $decimals = 0, $decPoint = '.', $thousandsSep = ',')
{
$price = number_format($number, $decimals, $decPoint, $thousandsSep);
$price = '$'.$price;
return $price;
}
}
RuntimeExtensionInterface是在 Symfony 3.4 中引入的
接下来,将类注册为服务并使用 标记它 twig.runtime。
文件:app\config\services.yml
services:
AppBundle\Twig\AppRuntime:
tags: [ twig.runtime ]
更多内容可参考:https://symfony.com/doc/3.4/templating/twig_extension.html