Skip to content

Magento 2 Display compare block only when the number of products to compare > 0

On the catalog page I only want to display the block-compare if the number of products to compare > 0. Now I still see the title of the comparison block, I don’t want to see anything.

This is my code:

<div class="block block-compare" data-bind="scope: 'compareProducts'" data-role="compare-products-sidebar">
    <div class="block-title " data-bind="css: {'no-display': !compareProducts().count}">
        <strong id="block-compare-heading" role="heading" data-bind="css: {'no-display': !compareProducts().count}" aria-level="2"><?= $block->escapeHtml(__('Compare Products')) ?></strong>
        <span class="counter qty no-display" data-bind="text: compareProducts().countCaption, css: {'no-display': !compareProducts().count}"></span>
    </div>
    <!-- ko if: compareProducts().count -->
    <div class="block-content no-display" aria-labelledby="block-compare-heading" data-bind="css: {'no-display': !compareProducts().count}">
        <ol id="compare-items" class="product-items product-items-names" data-bind="foreach: compareProducts().items">

...

enter image description here