문제

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
도움이 되었습니까?

해결책

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'));
        //...
    }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top