建立樹枝擴充套件

你可以在自定義 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());

官方文件中可以找到更多選項