2

I am trying to render template not using the Symfony2 required format 'Bundle:Controller:file_name', but want to render the template from some custom location.

The code in controller throws an exception

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

My code:

$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);

Is it even possible to do such things in Symfony, or we have to use only logical names format?

4

1 に答える 1

9

解決

最後の行を置き換えて、次のことができますreturn $this->render($tmpl);

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

use Symfony\Component\HttpFoundation\Response;ただし、コントローラーの上部にa を配置することを忘れないでください!

仮説

よし、今いるところから始めよう。あなたはコントローラーの中にいて、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;
}

メソッドを呼び出すと、テンプレートを表す文字列を使用して setContent が実行されrenderたプレーン オブジェクトである Response オブジェクトが返されることがわかりました。Response

もう少し詳しく説明したので、気にしないでください。このような解決策を自分で見つける方法を示すためにこれを行いました。

于 2013-01-14T14:59:50.203 に答える