错误:您无法创建非活动范围(“请求")的服务(“模板化.helper.assets")范围、模板、错误、quot

2023-09-06 23:56:58 作者:温情旅馆.

我遇到了错误,

  [Twig_Error_Runtime]                                                                                                                                                                                     
  An exception has been thrown during the rendering of a template ("You cannot create a    service ("templating.helper.assets") of an inactive scope ("request").") in "AcmeMessagingBundle:Comment:email.html.twig".

我正在从 symfony 2 自定义控制台命令渲染树枝模板

I am rendering twig template from symfony 2 custom console command

下面是我的服务类,它是事件订阅者,我正在通过 symfony 控制台命令触发 onCommentAddEmail 事件来发送电子邮件,

Below is my service class which is the event subscriber,I am triggering onCommentAddEmail event by symfony console command to send email,

class NotificationSubscriber implements EventSubscriberInterface
{
     private $container;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }


    public static function getSubscribedEvents()
    {
         return array(
            'comment.add'     => array('onCommentAddEmail', 0),
         );
     }

     public function onCommentAddEmail(CommentAddEvent $event)
     {
              ...................


             $body = $this->container->get('templating')->render(
            'AcmeMessagingBundle:Comment:email.html.twig',
                array('template' => $template)
             );

     .......


    }

}

$body 被传递给 swiftmailer 以发送电子邮件.

$body is passed to swiftmailer to send an email.

这是我的服务定义,

AcmeMessagingBundleSubscriberNotificationSubscriber

AcmeMessagingBundleSubscriberNotificationSubscriber

<services>
    <service id="notification_subscriber" class="%notification_subscriber.class%">
        <argument type="service" id="service_container" />
        <tag name="kernel.event_subscriber" />
    </service>
</services>

下面的帖子说问题已在 symfony 2.1 中修复,但我仍然收到错误,

Below post says the problem is fixed in symfony 2.1, but I am still getting error,

 https://github.com/symfony/symfony/issues/4514

我已经参考 http://symfony.com/doc/current/cookbook/service_container/scopes.html,我已将整个容器传递给我的服务.

I have already refereed to http://symfony.com/doc/current/cookbook/service_container/scopes.html, I have passed entire container to my service.

推荐答案

不确定这是否是最好的方法,但添加它对我有用,

Not sure if it is the best way but adding this worked for me,

    $this->container->enterScope('request');
    $this->container->set('request', new Request(), 'request');