TwigEngine.php 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Bundle\TwigBundle;
  11. use Symfony\Bridge\Twig\TwigEngine as BaseEngine;
  12. use Symfony\Bundle\FrameworkBundle\Templating\EngineInterface;
  13. use Symfony\Bundle\FrameworkBundle\Templating\TemplateReference;
  14. use Symfony\Component\Templating\TemplateNameParserInterface;
  15. use Symfony\Component\HttpFoundation\Response;
  16. use Symfony\Component\Config\FileLocatorInterface;
  17. /**
  18. * This engine renders Twig templates.
  19. *
  20. * @author Fabien Potencier <fabien@symfony.com>
  21. */
  22. class TwigEngine extends BaseEngine implements EngineInterface
  23. {
  24. protected $locator;
  25. /**
  26. * Constructor.
  27. *
  28. * @param \Twig_Environment $environment A \Twig_Environment instance
  29. * @param TemplateNameParserInterface $parser A TemplateNameParserInterface instance
  30. * @param FileLocatorInterface $locator A FileLocatorInterface instance
  31. */
  32. public function __construct(\Twig_Environment $environment, TemplateNameParserInterface $parser, FileLocatorInterface $locator)
  33. {
  34. parent::__construct($environment, $parser);
  35. $this->locator = $locator;
  36. }
  37. /**
  38. * {@inheritdoc}
  39. */
  40. public function render($name, array $parameters = array())
  41. {
  42. try {
  43. return parent::render($name, $parameters);
  44. } catch (\Twig_Error $e) {
  45. if ($name instanceof TemplateReference) {
  46. try {
  47. // try to get the real name of the template where the error occurred
  48. $name = $e->getTemplateName();
  49. $path = (string) $this->locator->locate($this->parser->parse($name));
  50. if (method_exists($e, 'setSourceContext')) {
  51. $e->setSourceContext(new \Twig_Source('', $name, $path));
  52. } else {
  53. $e->setTemplateName($path);
  54. }
  55. } catch (\Exception $e2) {
  56. }
  57. }
  58. throw $e;
  59. }
  60. }
  61. /**
  62. * {@inheritdoc}
  63. *
  64. * @throws \Twig_Error if something went wrong like a thrown exception while rendering the template
  65. */
  66. public function renderResponse($view, array $parameters = array(), Response $response = null)
  67. {
  68. if (null === $response) {
  69. $response = new Response();
  70. }
  71. $response->setContent($this->render($view, $parameters));
  72. return $response;
  73. }
  74. }