twig - pass function into template

Viewed 33407

Currently I place my function in a class and pass an instance of this class into template and call my required function as a class method.

{{ unneededclass.blah() }}

I need to do like below

{{ blah() }}

Is it possible?

5 Answers

Using Anonymous class

Create anonymous class in manager/controller/service ..

     $functions = new class($router)
    {
        public function __construct($router)
        {
            $this->router = $router;
        }

    public function getRowUrl(FileManager $fileManager)
    {
        if ($fileManager->isNode()) {
            return $this->router->generate('...', ['parent' => ...]);
        }
        return $this->router->generate('...', ['entity' => ...]);
    }
};

Paste parameter into view

$params=[
            'functions' => $functions

        ];



    return new Response($this->twig->render('...:index.html.twig', $params));

Use function in view

 {% set rowUrl = functions.rowUrl(entity) %}
Related