2012-04-24 93 views
13

而不是扩展标准控制器,我想将Twig注入到我的一个类中。在Symfony2中注入Twig作为服务

控制器:

namespace Project\SomeBundle\Controller; 

use Twig_Environment as Environment; 

class SomeController 
{ 
    private $twig; 

    public function __construct(Environment $twig) 
    { 
     $this->twig = $twig; 
    } 

    public function indexAction() 
    { 
     return $this->twig->render(
      'SomeBundle::template.html.twig', array() 
     ); 
    } 
} 

,然后在services.yml我有以下几点:

project.controller.some: 
    class: Project\SomeBundle\Controller\SomeController 
    arguments: [ @twig ] 

我得到的错误是:

SomeController :: __结构( )必须是Twig_Environment的一个实例,没有给出

但我通过config传递@twig。我看不到我做错了什么。

编辑:

添加在正确的代码 - 这就是解决了这一问题:

// in `routing.yml` refer to the service you defined in `services.yml` 
project.controller.some 
    project_website_home: 
     pattern:/
     defaults: { _controller: project.controller.some:index } 
+0

这看起来很老,但我想知道你是如何能够注册所有枝条扩展,在由SF2生成的代码具有 - > addExtension来动态添加这些代码。 – 2015-05-26 02:26:42

回答

5
  1. 尝试清除缓存。

  2. 您的路线设置为refer to the controller as a service?否则,Symfony不会使用服务定义,因此不会使用您指定的任何参数。所有的

+0

谢谢。这是routing.yml中不涉及该服务的路由。当你有访问容器的时候,使用routing.yml – ed209 2012-04-25 13:36:00

+0

的代码更新了这个问题,只需$ this-> container-> get('templating') - > render() – vodich 2016-08-31 12:16:25

3

首先,让我们了解一下什么是您的服务的容器可供选择:

λ php bin/console debug:container | grep twig 
    twig                 Twig_Environment 
    ... 

λ php bin/console debug:container | grep templa 
    templating               Symfony\Bundle\TwigBundle\TwigEngine 
    ... 

现在我们可能会去TwigEngine类(模板的服务),而不是Twig_Enviroment(小枝服务)。 你可以找到模板服务下vendor\symfony\symfony\src\Symfony\Bundle\TwigBundle\TwigEngine.php

... 
class TwigEngine extends BaseEngine implements EngineInterface 
{ 
... 

在这个类中,你会发现两个方法渲染(..)和 的renderResponse(...),这意味着你的代码的其余部分应正常工作与下面的例子。你还会看到TwigEngine注入了Twig服务(Twig_Enviroment类)来构造父类BaseEngine。因此,不需要请求枝条服务,并且请求Twig_Environment的错误应该消失。

所以,在你的代码会做像这样:

# app/config/services.yml 
services: 
    project.controller.some: 
     class: Project\SomeBundle\Controller\SomeController 
     arguments: ['@templating'] 

你的类

namespace Project\SomeBundle\Controller; 

use Symfony\Bundle\FrameworkBundle\Templating\EngineInterface; 
use Symfony\Component\HttpFoundation\Response; 

class SomeController 
{ 
    private $templating; 

    public function __construct(EngineInterface $templating) 
    { 
     $this->templating = $templating; 
    } 

    public function indexAction() 
    { 
     return $this->templating->render(
      'SomeBundle::template.html.twig', 
      array(

      ) 
     ); 
    } 
}