4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Bridge\Twig
;
14 use Symfony\Component\Templating\EngineInterface
;
15 use Symfony\Component\Templating\StreamingEngineInterface
;
16 use Symfony\Component\Templating\TemplateNameParserInterface
;
19 * This engine knows how to render Twig templates.
21 * @author Fabien Potencier <fabien@symfony.com>
23 class TwigEngine
implements EngineInterface
, StreamingEngineInterface
25 protected $environment;
31 * @param \Twig_Environment $environment A \Twig_Environment instance
32 * @param TemplateNameParserInterface $parser A TemplateNameParserInterface instance
34 public function __construct(\Twig_Environment
$environment, TemplateNameParserInterface
$parser)
36 $this->environment
= $environment;
37 $this->parser
= $parser;
43 * @param mixed $name A template name
44 * @param array $parameters An array of parameters to pass to the template
46 * @return string The evaluated template as a string
48 * @throws \InvalidArgumentException if the template does not exist
49 * @throws \RuntimeException if the template cannot be rendered
51 public function render($name, array $parameters = array())
53 return $this->load($name)->render($parameters);
59 * @param mixed $name A template name or a TemplateReferenceInterface instance
60 * @param array $parameters An array of parameters to pass to the template
62 * @throws \RuntimeException if the template cannot be rendered
64 public function stream($name, array $parameters = array())
66 $this->load($name)->display($parameters);
70 * Returns true if the template exists.
72 * @param mixed $name A template name
74 * @return Boolean true if the template exists, false otherwise
76 public function exists($name)
80 } catch (\InvalidArgumentException
$e) {
88 * Returns true if this class is able to render the given template.
90 * @param string $name A template name
92 * @return Boolean True if this class supports the given resource, false otherwise
94 public function supports($name)
96 if ($name instanceof \Twig_Template
) {
100 $template = $this->parser
->parse($name);
102 return 'twig' === $template->get('engine');
106 * Loads the given template.
108 * @param mixed $name A template name or an instance of Twig_Template
110 * @return \Twig_TemplateInterface A \Twig_TemplateInterface instance
112 * @throws \InvalidArgumentException if the template does not exist
114 protected function load($name)
116 if ($name instanceof \Twig_Template
) {
121 return $this->environment
->loadTemplate($name);
122 } catch (\Twig_Error_Loader
$e) {
123 throw new \
InvalidArgumentException($e->getMessage(), $e->getCode(), $e);