2013-01-14 41 views
2

我想呈現不使用Symfony2所需格式'Bundle:Controller:file_name'的模板,但想從某個自定義位置呈現模板。Symfony從自定義位置呈現模板

在控制器中的代碼拋出一個異常

Catchable Fatal Error: Object of class __TwigTemplate_509979806d1e38b0f3f78d743b547a88 could not be converted to string in Symfony/vendor/symfony/symfony/src/Symfony/Bundle/TwigBundle/Debug/TimedTwigEngine.php line 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的,或者我們只使用邏輯名稱格式?

+0

看看這一個http://stackoverflow.com/questions/12952309/symfony2-twig-default-template-file-in-custom-location – Subdigger

回答

8

解決方案

你可以做到以下幾點,免去您的最後一行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對象,使用表示字符串模板。

我希望你不介意我把它描述得更詳細些。我這樣做是爲了向你展示如何自己找到這樣的解決方案。

+0

感謝您的答案,我從它得到的主要事情是一個PHP應用程序/控制檯容器:調試。以前我試圖獲得加載器和樹枝環境,但沒有任何成功,這就是爲什麼我試圖創建一個新的環境和加載器實例。 – user1112057

+0

爲我工作:return $ this-> container-> get('templating') - > renderResponse –