问题
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?
回答1:
Instead of setting global twig var, read directly from the session in the template like so:
{% set cart = app.session.get('cart') %}
{{ cart|length }}
Or simply:
{{ app.session.get('cart')|length }}
This should give you the updated value (after the controller action has processed the data).
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) }}
This will sum all of the quantity values in the cart array (total quantity of items vs. number of unique items with length
)
EDIT:
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);
Then in the template:
{{ session.get('cart')|length }}
{# Or #}
{{ session.get('cart')|reduce((carry, v) => carry + v)}}
来源:https://stackoverflow.com/questions/58528052/how-to-get-the-current-session-array-count-in-twig