Symfony从自定义位置渲染模板

时间:2013-01-14 14:09:33

标签: symfony twig absolute-path

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

控制器中的代码抛出异常

  

Catchable Fatal Error:类的对象   __TwigTemplate_509979806d1e38b0f3f78d743b547a88无法转换为字符串   Symfony的/供应商/ symfony的/ symfony的/ SRC / Symfony的/捆绑/ TwigBundle /调试/ 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);

甚至可以在Symfony中执行此类操作,还是只使用逻辑名称格式?

1 个答案:

答案 0 :(得分:9)

<强>解决方案

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

$response = new Response();
$response->setContent($tmpl);
return $response;

不要忘记将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);
}

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

运行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;
}

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

我希望你不介意我更详细地描述它。我这样做是为了告诉你如何找到这样的解决方案。

相关问题