Get current template filename in Twig Extension

Viewed 563

I'm writing an extension for textblocks on my site. Therefore I made a twig extensions. As every textblock needs to be unique I included the template name in the filename of the textblock as well as a hook name. However I need to get the current template filename that called a twig extension.

It seems to be in the environment variable of twig, but is is not accessible.

My only workaround is to make the current template name a parameter of the function itself: {{ textblock_render('textblock_name', _self) }}, which seems a bit unnecessary.

So is there a way to get the current twig template filename, that called the extension?

class TextBlockExtension extends AbstractExtension
{

    public function getFunctions()
    {
        return [
            new TwigFunction('textblock_render', [$this, 'textblock'], ['is_safe' => ['html'], 'needs_environment' => true])
        ];
    }

    public function textblock(Environment $twig, string $hook, string $filename)
    {
        $loader = $twig->getLoader();

        if (preg_match(TextblockController::REGEX_TEXTBLOCK, $hook) === 1) {
            $path = '_partial/textblocks/' . md5('templates/' . $filename) . '-' . $hook . '.html.twig';

            if ($loader->exists($path)) {
                return $twig->render($path);
            }
        }
        return false;
    }
}
0 Answers
Related