1<?php
2
3/*
4 * This file is part of the Silex framework.
5 *
6 * (c) Fabien Potencier <fabien@symfony.com>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12namespace Silex\Application;
13
14use Symfony\Component\HttpFoundation\Response;
15use Symfony\Component\HttpFoundation\StreamedResponse;
16
17/**
18 * Twig trait.
19 *
20 * @author Fabien Potencier <fabien@symfony.com>
21 */
22trait TwigTrait
23{
24    /**
25     * Renders a view and returns a Response.
26     *
27     * To stream a view, pass an instance of StreamedResponse as a third argument.
28     *
29     * @param string   $view       The view name
30     * @param array    $parameters An array of parameters to pass to the view
31     * @param Response $response   A Response instance
32     *
33     * @return Response A Response instance
34     */
35    public function render($view, array $parameters = array(), Response $response = null)
36    {
37        $twig = $this['twig'];
38
39        if ($response instanceof StreamedResponse) {
40            $response->setCallback(function () use ($twig, $view, $parameters) {
41                $twig->display($view, $parameters);
42            });
43        } else {
44            if (null === $response) {
45                $response = new Response();
46            }
47            $response->setContent($twig->render($view, $parameters));
48        }
49
50        return $response;
51    }
52
53    /**
54     * Renders a view.
55     *
56     * @param string $view       The view name
57     * @param array  $parameters An array of parameters to pass to the view
58     *
59     * @return string The rendered view
60     */
61    public function renderView($view, array $parameters = array())
62    {
63        return $this['twig']->render($view, $parameters);
64    }
65}
66