Resolve local file path from Twig template name Resolve local file path from Twig template name symfony symfony

Resolve local file path from Twig template name


If you want to retrieve path from a controller you can use this code:

$parser = $this->container->get('templating.name_parser');$locator = $this->container->get('templating.locator');$path = $locator->locate($parser->parse('AcmeProjectBundle::home.html.twig'));

For more info take a look at code of:

  • Symfony\Bundle\FrameworkBundle\Templating\TemplateNameParser::parse
  • Symfony\Bundle\FrameworkBundle\Templating\Loader\TemplateLocator::locate


(To expand the answer of Molecular Man)

For the people needing this in Symfony 4:

The service templating.name_parser is not registered as such by default anymore and you need the dependency symfony/templating in Composer for it to be usable.
Also, it's recommended now to not use the container directly to get services (not to mention that the new AbstractController doesn't have all the services available), but rather do Dependency Injection by type-hinting.

So, the way to get it to work with Symfony 4:

//...use Symfony\Bundle\FrameworkBundle\Templating\Loader\TemplateLocator;use Symfony\Bundle\FrameworkBundle\Templating\TemplateNameParser;class DefaultController extends AbstractController{    public function indexAction(TemplateNameParser $parser, TemplateLocator $locator)    {        $path = $locator->locate($parser->parse('AcmeProjectBundle::home.html.twig'));        //...    }}