没有请求的Symfony2模板化

Mar*_*iry 8 symfony

我正在尝试从ContainerAwareCommandSymfony2 发送一封电子邮件.但是,当电子邮件模板呈现时,我得到此异常:

$body = $this->templating->render($template, $data);
Run Code Online (Sandbox Code Playgroud)

例外:

 ("You cannot create a service ("templating.helper.assets") of an inactive scope ("request").") 
Run Code Online (Sandbox Code Playgroud)

我在github中发现这个帮助器需要请求对象.有人知道如何实例化Request对象?

Bet*_*ide 19

您需要将容器设置为正确的范围并为其提供(假的)请求.在大多数情况下,这就足够了:

//before you render template add bellow code
$this->getContainer()->enterScope('request');
$this->getContainer()->set('request', new Request(), 'request');
Run Code Online (Sandbox Code Playgroud)

完整的故事就在这里.如果您想了解详细信息,请在github上阅读此问题.


Mat*_*hew 1

由于您没有请求,因此需要直接调用模板服务,如下所示:

$this->container->get('templating')->render($template, $data);
Run Code Online (Sandbox Code Playgroud)

  • 这并不能解决问题。当使用登录资产时(很可能在模板中不直接可见),它需要以某种方式拥有 RequestContext 服务。 (3认同)