创建树枝扩展
你可以在自定义 Twig_Extension
类中对所有自定义函数/ filters / tests / …进行分组:
ProjectTwigExtension
class ProjectTwigExtension extends Twig_Extension {
public function getFunctions() {
return array(
new Twig_SimpleFunction('twig_function_name', array($this, 'getTwigFunctionName')),
new Twig_SimpleFunction('twig_function_foo', array($this, 'getTwigFunctionFoo')),
);
}
public function getFilters() {
return array(
new Twig_SimpleFilter('twig_filter_name' , array($this, 'getTwigFilterName')),
new Twig_SimpleFilter('twig_filter_foo' , array($this, 'getTwigFilterFoo')),
);
}
public function getName() {
return 'ProjectTwigExtension';
}
}
在树枝上注册扩展名
$twig = new Twig_Environment($loader);
$twig->addExtension(new ProjectTwigExtension());
官方文档中可以找到更多选项