如何在树枝中获取当前会话数组计数? [英] How to get the current session array count in twig?

查看:65
本文介绍了如何在树枝中获取当前会话数组计数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我实例化我的树枝的引导文件中:

In my bootstrap file where I instantiate my twig I have:

$twig->addGlobal('cart', $session->get('cart'));

在我的树枝的顶部导航栏中,我有一个徽章来显示购物车中添加的商品数量,如下所示:

and in top navbar of my twig I have a badge to show how many items are in added in cart as below:

{{ cart|length }}

和我上面说的引导文件之后调用的主文件,我有:

and my main file that is called after bootstrap file I said above, I have:

if (!empty($_getvars['id'])) {
    $data = $session->get('cart');
    if(!isset($data[$_getvars['id']])) {
        $data[$_getvars['id']] = 0;
    }
    $data[$_getvars['id']] += 1;
    $session->set('cart', $data);
} 
print_r($session->get('cart'));

添加到会话工作正常,上面的打印调试显示它是准确的,但在顶部导航栏徽章中,我总是获得以前的项目数量而不是当前数量,除非我刷新页面以显示当前数量.如何解决?

adding to sessions is working fine, and print debug above shows that it is accurate, but in the top navbar badge I always get the previous amount of items rather than current amount unless otherwise I refresh the page to show the current. How to fix it?

推荐答案

不是设置全局 twig var,而是直接从模板中的会话中读取,如下所示:

Instead of setting global twig var, read directly from the session in the template like so:

{% set cart = app.session.get('cart') %}
{{ cart|length }}

或者干脆:

{{ app.session.get('cart')|length }}

这应该会给你更新的值(在控制器操作处理完数据之后).

This should give you the updated value (after the controller action has processed the data).

但是,查看您的相关问题,我认为您需要 array_sum() 而不是 length,在 twig 中您可以使用 reduce过滤器:

However, looking at your related questions, I think you want array_sum() instead of length, in twig you can use the reduce filter:

{{ app.session.get('cart')|reduce((carry, v) => carry + v) }}

这将对购物车数组中的所有数量值求和(商品的总数与具有 length 的唯一商品的数量)

This will sum all of the quantity values in the cart array (total quantity of items vs. number of unique items with length)


对于独立应用程序,如 DarkBee 所述,您可以将会话对象添加为全局而不是会话购物车值.


For a stand-alone app, as mentioned by DarkBee, you could just add the session object as global instead of the session cart value.

$twig->addGlobal('session', $session);

然后在模板中:

{{ session.get('cart')|length }}
{# Or #}
{{ session.get('cart')|reduce((carry, v) => carry + v)}}

这篇关于如何在树枝中获取当前会话数组计数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆