twig Extending twig Creating a Twig_Extension


Example

You can group all your custom functions/filters/tests/... inside a custom Twig_Extension class:

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';
    }        
}

Register extension in twig

$twig = new Twig_Environment($loader);
$twig->addExtension(new ProjectTwigExtension());

More options can be found on the official docs