在Symfony 3.4中,base.html.twig我有一个导航栏,显示当前用户的消息数。我使用存储库实体函数来执行此操作。每次模板base.html.twig渲染时都必须调用此函数,但我不想在所有控制器中将此函数放在事件监听器之前如何在渲染base.html.twig之前执行此操作?覆盖基础控制器?
base.html.twig :
....
{{ include top_bar_nav.html.twig }}
....
答案 0 :(得分:1)
自定义Twig扩展名是正确的方法:
树枝上的例子:{{ number_of_current_users() }}
像这样创建twig扩展名:
<?php
namespace AppBundle\Twig;
use Doctrine\ORM\EntityRepository;
class UserExtension extends \Twig_Extension
{
/**
* @var EntityRepository
*/
private $userRepository;
/**
* @param EntityRepository $repository
*/
public function __construct(EntityRepository $repository)
{
$this->userRepository = $repository;
}
/**
* {@inheritdoc}
*/
public function getFunctions()
{
return array(
new \Twig_SimpleFunction('number_of_current_users', array($this, 'numberOfCurrentUsers')),
);
}
/**
* @param $sku
*
* @return string
*/
public function numberOfCurrentUsers()
{
return $this->userRepository->getNumberOfCurrentUsers();
}
/**
* {@inheritdoc}
*/
public function getName()
{
return 'user';
}
}
并将其注册为:
app.twig.users:
class: AppBundle\Twig\UserExtension
arguments: ['INJECT YOUR USER REPOSITORY HERE']
public: false
tags:
- { name: twig.extension }