Symfony从自定义位置渲染模板

use*_*057 2 absolute-path symfony twig

我试图渲染模板不使用Symfony2所需格式'Bundle:Controller:file_name',但想要从某个自定义位置渲染模板.

控制器中的代码抛出异常

可捕获的致命错误:类__TwigTemplate_509979806d1e38b0f3f78d743b547a88的对象无法在Symfony/vendor/symfony/symfony/src/Symfony/Bundle/TwigBundle/Debug/TimedTwigEngine.php第50行中转换为字符串

我的代码:

$loader = new \Twig_Loader_Filesystem('/path/to/templates/');
$twig = new \Twig_Environment($loader, array(
    'cache' => __DIR__.'/../../../../app/cache/custom',
));
$tmpl = $twig->loadTemplate('index.twig.html');
return $this->render($tmpl);
Run Code Online (Sandbox Code Playgroud)

甚至可以在Symfony中做这样的事情,或者我们只能使用逻辑名称格式?

Sgo*_*kes 9

您可以执行以下操作,替换最后一行return $this->render($tmpl);:

$response = new Response();
$response->setContent($tmpl);
return $response;
Run Code Online (Sandbox Code Playgroud)

不要忘记把use Symfony\Component\HttpFoundation\Response;控制器放在控制器的顶部!

理论

好吧,让我们从你现在的位置开始吧.你在控制器内,调用render方法.该方法定义如下:

/**
 * Renders a view.
 *
 * @param string   $view       The view name
 * @param array    $parameters An array of parameters to pass to the view
 * @param Response $response   A response instance
 *
 * @return Response A Response instance
 */
public function render($view, array $parameters = array(), Response $response = null)
{
    return $this->container->get('templating')->renderResponse($view, $parameters, $response);
}
Run Code Online (Sandbox Code Playgroud)

docblock告诉您它需要一个字符串作为视图名称,而不是实际模板.如您所见,它使用templating服务并简单地传递参数并来回返回值.

Running php app/console container:debug显示所有已注册服务的列表.你可以看到这templating是一个实际的实例Symfony\Bundle\TwigBundle\TwigEngine.该方法renderResponse具有以下实现:

/**
 * Renders a view and returns a Response.
 *
 * @param string   $view       The view name
 * @param array    $parameters An array of parameters to pass to the view
 * @param Response $response   A Response instance
 *
 * @return Response A Response instance
 */
public function renderResponse($view, array $parameters = array(), Response $response = null)
{
    if (null === $response) {
        $response = new Response();
    }

    $response->setContent($this->render($view, $parameters));

    return $response;
}
Run Code Online (Sandbox Code Playgroud)

您现在知道,当您调用该render方法时,将传回一个Response对象,该对象本质Response上是一个执行setContent 的普通对象,使用表示该模板的字符串.

我希望你不介意我把它描述得更详细一些.我这样做是为了告诉你如何自己找到这样的解决方案.