return 来自 symfony 中的函数作为树枝模板中的全局函数

return result from function in symfony as global in twig templates

我有一个函数 returns 购物车中的商品数量。如何在网站的每个页面上显示这个数字?我需要在站点所有页面中加载的树枝文件中显示它的值...

这是我想使用的功能:

public function getCartCount(){

  $session = new Session();

  $session_user =  $session->get('temp_session_user');

  $em = $this->doctrine->getManager();  

  $details = $em->getRepository('AppBundle:RechargeLogs')->findBy(array(

        'sessionVal'=> $session_user,

        'status'=> 0

  ));

这个问题有很多解决方法,

您可以创建一个树枝过滤器: https://symfony.com/doc/current/templating/twig_extension.html

你可以在树枝中嵌入控制器: http://symfony.com/doc/current/templating/embedding_controllers.html

您可以在会话中存储变量并在树枝中访问它: https://symfony.com/doc/current/templating/app_variable.html

您甚至可以创建服务并将其注册为 twig 中的全局变量并使用它: https://symfony.com/doc/current/templating/global_variables.html#referencing-services