Magento 2 - need super simple way of assessing whether cart is empty or not in list.phtml file
Question
Client wants to display a conditional message on the category list.phtml page depending on whether or not the cart has ANYTHING in it
I've found a lot of posts about creating a custom module to be able to assess cart items etc. but surely there must just be a simple way of identifying whether the cart contains anything or not without the need for a whole module to do so.
I don't care if we're counting items, reporting totals, assessing whether a cart exists or however it's done I just need a 'cart_empty' true or false variable
Any ideas?
UPDATED: reading a little more on this, I think the issue may be because we have caching in place on the product list page for performance reasons
This being the case do I need to access the cart using AJAX in some way?
Solution
You should use minicart knockout, otherwise cache will be a problem. Just name the scope different like 'cart_check'. In your list.phtml
<div data-bind="scope: 'cart_check'">
<!-- ko ifnot: getCartParam('summary_count') -->
<div class="block-content no-display"
data-bind="css: {'no-display': getCartParam('summary_count')}">
<span>NO ITEMS IN CART</span>
</div>
<!-- /ko -->
</div>
and
<script type="text/x-magento-init">
{
"*": {
"Magento_Ui/js/core/app": {
"components": {
"cart_check": {
"component": "Magento_Checkout/js/view/minicart"
}
}
}
}
}
</script>
OTHER TIPS
Maybe below is the simple way in any list.phtml file.
$cartHelper = $this->helper(Magento\Checkout\Helper\Cart::class);
if ($cartHelper->getItemsCount() === 0) {
// write your code
}