Symfony/Twig:在Twig模板中打印函数返回值


Symfony/Twig : print a function return in twig template

我想这样做:

{{ users_number() }} or {{ users_number }}

在Twig的模板中。我的服务是这样的:

class HomeExtension extends 'Twig_Extension
 {
   public function getFunction()
    {
        return array(
            new 'Twig_SimpleFunction('users_number', array($this, 'getUsersNb'))
        );
    }
    public function getName()
    {
        return 'users_number';
    }
    public function getUsersNb(){
        $em = $this->getDoctrine()->getManager();
        $countUsers = $em->getRepository("ASDPUsersBundle:Users")->getNb();
        return $countUsers;
    }
}

我仍然不能在我的视图中得到我的值。我怎么能做到呢?还是我在服务中遗漏了什么?

编辑:我这样注册我的服务:

services:
 users_number:
  class: ASDP'HomeBundle'Twig'Extension'HomeExtension
  tags:
   - { name : twig.extension }

试试这个:

public function getFunctions()
{
    return array(
        new 'Twig_SimpleFunction('users_number', array($this,'getUsersNb')))
    );
}

和您的扩展必须扩展'Twig_Extension和服务必须有标签twig。扩展:

<service class="Vendor'Bundle'Twig'Extension'YourExtension" id="your.extension.id">
  <tag name="twig.extension"/>
</service> 

OR在Yaml:

your.extension.id:
    class: Vendor'Bundle'Twig'Extension'YourExtension
    tags:
        - { name: twig.extension }

您需要在您的Twig扩展服务中注入实体管理器

your.extension.id:
    class: Vendor'Bundle'Twig'Extension'YourExtension
    arguments: ["@doctrine.orm.entity_manager"]
    tags:
        - { name: twig.extension }

然后在您的自定义扩展中使用它:

protected $em;
public function __construct($em)
{
    $this->translator = $translator;
}
// ...
public function getUsersNb()
{
    $countUsers = $this->em->getRepository("ASDPUsersBundle:Users")->getNb();
    return $countUsers;
}