解決方案
你可以做到以下幾點,免去您的最後一行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);
}
的文檔塊告訴你,它需要一個字符串這是視圖名稱,而不是實際的模板。如您所見,它使用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
對象,使用表示字符串模板。
我希望你不介意我把它描述得更詳細些。我這樣做是爲了向你展示如何自己找到這樣的解決方案。
看看這一個http://stackoverflow.com/questions/12952309/symfony2-twig-default-template-file-in-custom-location – Subdigger