如何输出购物车商品编号?

How can I output the Cart item number?

我想知道如何显示购物车中有多少商品?我在树枝上做了一条路,但我不确定如何显示它。

这是我的控制器,我有路线,在树枝中我用名称 (count_panier) 调用路径。

/**
    * @Route("/count/{qtt}", name="count_panier")
    */
    public function testAction($qtt,Request $req)
    {
       
       $qtt = $this->afficherCount($req);

       
        
      return $this->redirectToRoute('mag',['count'=>$qtt]);
                                                        
    }

//----------------------------------------------

    public function afficherCount(Request $req){

      $sess = $req->getSession();

      $panier = $sess->get('panier',[]);

      $qtt = 0;

      foreach($panier as $item)
      {
        $qtt += $item->quantiteCommandee;
      }

    
    
      return $qtt;


    }

这是我的树枝,这是顶部导航栏的一部分

    <div class="menu">
        <a class="active" href="{{path('mag')}}">Catalogue</a>
        <a href="contact">Contact</a>
        <a href="#creeCompte">Crée un compte</a>
        <a href="#connexion">Connexion</a>
        <a href="panier">Panier
        <img width="30" alt="img" src="{{asset('images/cart.png')}}"/></a>

        <span id='panierCompteur'>
        
         <a href="{{ path('count_panier', {'qtt': 0}) }}"></a> 

         items</span>
    </div>

在您的控制器中,您只传递了一个参数 count => '$qtt

所以在 Twig 文件中,如果你想获取它,请执行以下操作:

{{ count }}

因此,如果您想获得显示您拥有多少物品的 link,请执行以下操作:

 <span id='panierCompteur'>
        
         <a href="{{ path('count_panier'}}"> {{count}} </a> 

         items</span>

(你没有使用 $qtt 变量所以不要传递它)

/**
    * @Route("/count", name="count_panier")
    */
    public function testAction(Request $req)
    {
       
       $qtt = $this->afficherCount($req);

       
      return $this->redirectToRoute('mag',['count'=>$qtt]);                                         
    }

//----------------------------------------------

    private function afficherCount(Request $req){

      $sess = $req->getSession();

      $panier = $sess->get('panier',[]);

      $qtt = 0;

      foreach($panier as $item)
      {
        $qtt += $item->quantiteCommandee;
      }

   
      return $qtt;
    }

当然,第一次呈现此主页时,您需要 运行 索引控制器(或任何主控制器)中的函数 afficherCount() 和 return 到主页 count => '$qtt 以及所有其他参数。

你正在重定向到另一个路由,所以如果你想获得这些参数,你需要“处理”重定向:

   /**
    * @Route("/your-route/{count?}", name="mag", requirements={"count"="\d+"})
    */
    public function yourFunction(Request $req, $count)
    {
      // true if is the first time you render this page or if you don't pass the value
      if($count === null){
         $count = afficherCount($req);
      }

      return $this->Render('yourTwigFile.html.twig',['count'=>$count]);                                         
    }

{count?} : ? if 为可选参数,因此第一次呈现此页面时无需传递 URL

中的值

requirements={"count"="\d+"} : 值只能是整数

(PS。这个函数大概就是你的索引)