简体   繁体   English

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

[英]Symfony/Twig : print a function return in twig template

I'd like to do something like : 我想做类似的事情:

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

in a Twig's template. 在Twig的模板中 My service looks like this : 我的服务如下所示:

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;
    }
}

Still, i can't get my value in my view. 不过,我仍然无法获得自己的价值。 How could i do it ? 我该怎么办? Or did i miss something in my service ? 还是我错过了我的服务?

Edit: I registered my service like this : 编辑:我这样注册我的服务:

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

Is it the right way ? 这是正确的方法吗?

Try this: 尝试这个:

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

And your extension must extend \\Twig_Extension and service must have tag twig.extension : 并且您的扩展名必须扩展\\ Twig_Extension,并且服务必须具有标签twig.extension:

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

OR in Yaml: 或在Yaml中:

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

You need to inject the entity manager on your Twig Extension Service 您需要在Twig Extension Service上注入实体管理器

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

And then use it in your custom extension: 然后在自定义扩展中使用它:

protected $em;

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

// ...

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

I hope it helps. 希望对您有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM