From 438b6ac705fde164d851c94ec231297474bea525 Mon Sep 17 00:00:00 2001 From: Andrey Kutejko Date: Sat, 16 Mar 2019 12:32:13 +0100 Subject: [PATCH] allow to specify template functions --- ipf/template.php | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/ipf/template.php b/ipf/template.php index 619b630..72bd514 100644 --- a/ipf/template.php +++ b/ipf/template.php @@ -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] + )); + } } } -- 2.49.0