我想做一些类似的事情:
{{ 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 }这条路对吗?
发布于 2015-05-15 00:19:31
试试这个:
public function getFunctions()
{
return array(
new \Twig_SimpleFunction('users_number', array($this,'getUsersNb')))
);
}并且您的扩展必须扩展\Twig_Extension,并且服务必须具有标记twig.extension:
<service class="Vendor\Bundle\Twig\Extension\YourExtension" id="your.extension.id">
<tag name="twig.extension"/>
</service> 或者在Yaml中:
your.extension.id:
class: Vendor\Bundle\Twig\Extension\YourExtension
tags:
- { name: twig.extension }发布于 2015-05-15 03:00:04
您需要在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;
}我希望它能帮上忙。
https://stackoverflow.com/questions/30242019
复制相似问题