phpsymfonytwigtwig-extension

How to call built-in twig function from custom twig filter?


I want to create a custom filter which will return HTML link to client profile.

I need something like:

<?php

namespace App\Twig;

use App\Entity\Client;
use Twig\Environment;
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;

class ClientExtension extends AbstractExtension
{
    /**
     * {@inheritdoc}
     */
    public function getFilters(): array
    {
        return [
            new TwigFilter('client_link', [$this, 'createClientLink'], [
                'is_safe' => ['html'],
                'needs_environment' => true,
            ]),
        ];
    }

    public function createClientLink(Environment $environment, Client $client): string
    {
        // this code is an example, such function does not exist
        $url = $environment->callTwigFunction('path', 'client_profile', [$client->getId()]);
        return '<a href="'.$url.'">'.$client->getEmail().'</a>';
    }
}

What I cannot figure out is how do I call the path twig function? Is there some callTwigFunction-like feature I can use?


Solution

  • I have implemented it this way:

    $url = $environment->getExtension(Symfony\Bridge\Twig\Extension\RoutingExtension\RoutingExtension::class)->getPath('cp_client_show_summary', ['id' => $client->getId()]);
    

    Thanks to the suggestion of @Cerad

    EDIT:

    I am going to keep the above code because it shows the answer to the more general question I had about "calling built-in twig functions from inside filters". However as pointed by others in the comments, the proper way for my case was to inject UrlGeneratorInterface:

    class AppExtension extends AbstractExtension
    {
        public function __construct(
            private readonly UrlGeneratorInterface $urlGenerator,
        ) {
        }
    
        //...
    

    and then generate URL like this:

    $url = $this->urlGenerator->generate('cp_client_show_summary', ['id' => $client->getId()]);