Extending Twig in theme PHP file


#1

Would it be possible to add functions to Twig within the theme PHP file (IE: antimatter.php)?


#2

Yes! In the class named after the theme inside a method onTwigExtensions, you can add something like:

// ...
   public function onTwigExtensions()
   {
       $function = new \Twig_SimpleFunction ('mytest', function () {
           return "This is a test.";
       });
       $this->grav['twig']->twig->addFunction($function);                   
   }

// ...

And use it in Twig with {{ mytest() }}.


#3

@punchfighter in addition to @Utis comment read this (extend twig)