I'm looking for an easy way to show on my template a cart icon only if the cart has 1 or more elements (Drupal 8, commerce 2.x); I've tried with a view, but I had problems to identify the cart associated to the current (normally anonymous) user.

Does that easy way exist?

Can anyone point me in the right direction? I've searched on Commerce 2.x docs, but I didn't find anything about the feature I'd like to implement. (I don't want to show the cart, only show an icon when the cart exists and has items.)

I've also used suggestions found on How do I count the number of products in cart programmatically? and I was able to create a twig variable using theme preprocess function, but the variable is never updated. Is it mandatory to develop a module?

1 Answer 1


Don't know any module that does this but it is simple to do in your theme

Add this to your THEMENAME.theme

function THEMENAME_preprocess_block(&$variables) {
  if ($variables['plugin_id'] == 'commerce_cart') {
    if ($variables['content']['#count'] == 0) {
      $variables['attributes']['class'][] = 'visually-hidden';
  • Thank you very much, I'll try it soon
    – NotHere
    Jun 16, 2020 at 5:36

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.