let\'s say I have created a custom twig function: templateName.
$twig = new Twig_Environment($loader);
$twig->addFunction(\'templateName\', new Twig_Func
$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.