2013-02-01 163 views
1

在Symfony2的项目中使用的树枝,我已经创建了一个实现Twig_ExtensionInterface这样我就可以把它作为一个嫩枝过滤服务,像{{ stuff|my_filter }}在自定义的树枝扩展

在这个服务,我需要用小树枝环境在所以我可以使用例如树枝模板,所以我注入它作为一个可以在服务做到:

services: 
    meta.twig.my_extension: 
     class: Acme\GeneralBundle\Twig\MyExtension 
     tags: 
      - { name: twig.extension } 
     arguments: 
      twig: "@twig" 

所以本身的服务看起来像:

在services.yml
<?php 

namespace Acme\GeneralBundle\Twig; 

class MyExtension extends \Twig_Extension 
{ 

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

    public function getFilters() 
    { 
     return array(
      'my_filter' => new \Twig_Filter_Method($this, 'myFunction'), 
     ); 
    } 

    public function myFunction($text) 
    { 
     return $this->twig->render($someTemplate,$someArguments); 
    } 
} 

我能在那样的控制器使用方法:

$myService = $this->container->get('Acme.twig.my_extension'); 
$text = $myService->myFunction($someValue); 

但是,当然,我得到一个CircularReference错误这样做时:

Circular reference detected for service "Acme.twig.my_extension", 
path: "Acme.twig.my_extension -> twig". 

那么,什么是在自定义Twig过滤器中使用twig-> render()函数的最佳方法是什么?

非常感谢!

+1

你使用什么版本的symfony?在2.1我没有看到问题和这样的例子,因为你的工作没有问题。您可以尝试注入容器而不是twig_env和延迟加载树枝。 – l3l0

+1

我正在使用版本2.1.8-DEV,但这个例子不起作用。我明白,注入整个容器是不好的做法,这就是为什么我走这条路......没有效果,因为有效地,树枝环境似乎是以某种方式“递归地注入”的。我在网上找不到任何文献以获得一个好的解决方案 – tchap

+0

您是否尝试删除扩展的构造函数和服务文件中的参数部分? DIC应该照顾你。 –

回答

3

Twig_ExtensionInterface定义了接受树枝环境作为参数的initRuntime()方法。此方法在初始化扩展时由枝条调用。

您已将Twig_Extension课程延伸,其中already provides an empty implementation of this method。你所要做的就是覆盖它并存储一个引用到树枝环境以供将来使用。

<?php 

namespace Acme\GeneralBundle\Twig; 

class MyExtension extends \Twig_Extension 
{ 
    private $environment = null; 

    public function initRuntime(\Twig_Environment $environment) 
    { 
     $this->environment = $environment; 
    } 

    public function getFilters() 
    { 
     return array(
      'my_filter' => new \Twig_Filter_Method($this, 'myFunction'), 
     ); 
    } 

    public function myFunction($text) 
    { 
     return $this->environment->render($someTemplate,$someArguments); 
    } 
} 

文档:Creating an extension

+0

是的,这在我确实在树枝模板中使用该服务时有效。但是,我怎么把它称为服务,如下所示:$ myService = $ this-> container-> get('Acme.twig.my_extension'); $ text = $ myService-> myFunction($ someValue); ...我需要以某种方式通过树枝环境 – tchap

+0

Twig环境在loadTemplate()中自动调用方法。我想你可以强制通过调用$ twig-> initRuntime()来初始化所有扩展。 –