ojreadmore
ojreadmore

Reputation: 1475

Resolve local file path from Twig template name

What are the programmatic steps to turn this string:

AcmeProjectBundle::home.html.twig

into this?

/path/Symfony/src/Acme/ProjectBundle/Resources/views/home.html.twig

Upvotes: 16

Views: 6160

Answers (2)

Dennis98
Dennis98

Reputation: 139

(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'));
        //...
    }
}

Upvotes: 0

Molecular Man
Molecular Man

Reputation: 22386

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

Upvotes: 26

Related Questions