]> git.andy128k.dev Git - ipf.git/commitdiff
allow to specify template functions
authorAndrey Kutejko <andy128k@gmail.com>
Sat, 16 Mar 2019 11:32:13 +0000 (12:32 +0100)
committerAndrey Kutejko <andy128k@gmail.com>
Sat, 16 Mar 2019 11:32:13 +0000 (12:32 +0100)
ipf/template.php

index 619b630245ec6cf2e90afae872d772d0cf029572..72bd514a46d7a4ce3ab1aa8740a9df051e253abd 100644 (file)
@@ -16,6 +16,7 @@ use Twig\TwigFunction;
 interface TemplateEnvironment
 {
     function render($template, $context = [], $request = null);
+    function addFunction($name, $callable);
 }
 
 class TemplateEnvironmentTwig implements TemplateEnvironment
@@ -31,6 +32,8 @@ class TemplateEnvironmentTwig implements TemplateEnvironment
     /** @var IPF_Router */
     private $router;
 
+    private $customFunctions = [];
+
     public function __construct(IPF_Settings $settings, array $processors, array $apps, LoaderInterface $loader, IPF_Router $router)
     {
         $this->settings = $settings;
@@ -52,6 +55,11 @@ class TemplateEnvironmentTwig implements TemplateEnvironment
         return $template->render($context);
     }
 
+    public function addFunction($name, $callable)
+    {
+        $this->customFunctions[$name] = $callable;
+    }
+
     private function createEnvironment()
     {
         $options = array(
@@ -106,6 +114,15 @@ class TemplateEnvironmentTwig implements TemplateEnvironment
         $twig->addFunction(new TwigFunction('trans', function ($str) {
             return __($str);
         }));
+        foreach ($this->customFunctions as $name => $callable) {
+            $twig->addFunction(new TwigFunction(
+                $name,
+                function (/* $context, ...$args */) use ($callable) {
+                    return call_user_func_array($callable, func_get_args());
+                },
+                ['needs_context' => true]
+            ));
+        }
     }
 }