2012-04-24 41 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(

      ) 
     ); 
    } 
}