How to get current template name in a TWIG function

后端 未结 3 507
无人共我
无人共我 2021-01-19 08:43

let\'s say I have created a custom twig function: templateName.

$twig = new Twig_Environment($loader);
$twig->addFunction(\'templateName\', new Twig_Func         


        
3条回答
  •  醉话见心
    2021-01-19 09:13

    $twig = new Twig_Environment($loader);
    $twig->addFunction(new Twig_SimpleFunction('twig_template_name', function() use ($twig) {
    
      $caller_template_name = $twig->getCompiler()->getFilename();
    
      echo "This function was called from {$caller_template_name}";
    
    }));
    

    UPDATE: as mentioned by Leto, this method will NOT work from within cached (compiled) templates. If, however, you use shared memory caching (APC, Memcache) instead of Twig's caching or run this functionality in app that runs in an environment that doesn't have high traffic (think of back-end app for staff or branch of app that is only used to collect information about app's codebase) you can make it work by disabling Twig's caching (e.g. $twig = new Twig_Environment($loader, array('cache' => false));). Make sure to carefully examine your use case though before disabling Twig's cache and using this method and see if you can solve that problem using different approach.

提交回复
热议问题