本文介绍了错误:您无法创建非活动范围(“请求")的服务(“templating.helper.assets")的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到以下错误,

  [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.

这是我的服务定义,

Acme\MessagingBundle\Subscriber\NotificationSubscriber

Acme\MessagingBundle\Subscriber\NotificationSubscriber

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

这篇关于错误:您无法创建非活动范围(“请求")的服务(“templating.helper.assets")的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 09:25