Magento – Magento 2: How to show the number of cart items in a custom block

cartknockoutjsmagento-2.1templateui

The easiest way to show the number of cart items in a block would be via PHP, but that would mean disabling caching for the block (and hence the entire page)

Does anyone know how to display the cart item counter in a phtml file using knockoutJS? I've seen this (and equivalents) around:

<!-- ko text: getCartParam('summary_count') --><!-- /ko -->

But it returns the error:

Message: getCartParam is not defined

So I assume it needs to be prepared in the layout XML file or something.

I found that adding:

data-bind="scope: 'minicart_content'"

To the parent element got rid of the error, but it still doesn't output anything.

Any clues?

Best Answer

I accomplished this by adding the minicart UI component to my block, which allowed me to display the summary_count variable. My XML looked something like this:

<block class="Magento\Framework\View\Element\Template" name="my-block" template="My_Module::my-template.phtml">
    <arguments>
        <argument name="jsLayout" xsi:type="array">
            <item name="components" xsi:type="array">
                <item name="my-item-count" xsi:type="array">
                    <item name="component" xsi:type="string">Magento_Checkout/js/view/minicart</item>
                </item>
            </item>
        </argument>
    </arguments>
</block>

And then in my-template.phtml I initialised it like this:

<span id="cart-items" data-bind="scope:'my-item-count'">
    <!-- ko text: getCartParam('summary_count') --><!-- /ko -->
</span>

<script type="text/x-magento-init">
    {
        "#cart-items": {
            "Magento_Ui/js/core/app": <?php /* @escapeNotVerified */ echo $block->getJsLayout();?>
        }
    }
</script>