16

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
7
  • Are you asking for the algorithm used? Or for an actual function you can call? Keep in mind that this is all done during the "compile" phase with the results stored in the cache. Not something that you would normally deal with during run time.
    – Cerad
    Feb 17, 2012 at 15:45
  • The functions used within twig/symfony.
    – ojreadmore
    Feb 17, 2012 at 19:40
  • See Symfony\Bundle\FrameworkBundle\Templating\TemplateNameParser
    – solarc
    Feb 17, 2012 at 22:13
  • hmm, vendor/symfony/src/Symfony/Bundle/FrameworkBundle/Templating/Loader/TemplateLocator.php looks promising
    – ojreadmore
    Feb 24, 2012 at 16:37
  • Can I access the Kernel object from a controller, or at least something that can lead me to it?
    – ojreadmore
    Feb 24, 2012 at 17:01

2 Answers 2

26
+50

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
0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.