1

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?

0

1 Answer 1

5

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)}}
Sign up to request clarification or add additional context in comments.

4 Comments

This is not framework. This is standalone. So how to get/import app in standalone usage?
@user4271704 why did you tag your question with symfony then?
This is symfony session component but standalone.
You could add the session object as global rather than the integer cart then

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.