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
ojreadmore
  • 1,465
  • 2
  • 17
  • 33
  • 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 '12 at 15:45
  • The functions used within twig/symfony. – ojreadmore Feb 17 '12 at 19:40
  • See Symfony\Bundle\FrameworkBundle\Templating\TemplateNameParser – solarc Feb 17 '12 at 22:13
  • hmm, vendor/symfony/src/Symfony/Bundle/FrameworkBundle/Templating/Loader/TemplateLocator.php looks promising – ojreadmore Feb 24 '12 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 '12 at 17:01
  • @carlosz is right. TemplateNameParser is the class. However you can't view any value on the file because the class is cached at app/cache/[env]/classes.php and loaded from there. – Mun Mun Das Feb 25 '12 at 13:10
  • Check http://stackoverflow.com/questions/7585474/accessing-files-relative-to-bundle-in-symfony2 – Mark Fu Jul 03 '12 at 09:34

2 Answers2

26

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
Molecular Man
  • 22,277
  • 3
  • 72
  • 89
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'));
        //...
    }
}
Dennis98
  • 139
  • 1
  • 12