Magento 2 – How to Rewrite Minicart default.html with phtml

layoutmagento2mini-cart

I have created a file app/design/frontend/my_vendor/my_theme/Magento_Checkout/web/template/minicart/item/default.html to write the Magento 2 standard mini cart default.html. And this is working fine.

However, I need to add some PHP code into my default.html. Can I change this to default.phtml, so I can add PHP code? and how do I tell the system to use default.phtml as the mini cart template? I can't find a layout.xml where we can define the file name.

Best Answer

Magento 2 using private content and KnockoutJs for load minicart.

Example add price row total to minicart.

Override DefaultItem customer data Magento\Checkout\CustomerData\DefaultItem

<preference for="Magento\Checkout\CustomerData\DefaultItem" type="Your_Vendor\Module\CustomerData\DefaultItem"/>

Add row total to doGetItemData function

protected function doGetItemData()
    {
        $imageHelper = $this->imageHelper->init($this->getProductForThumbnail(), 'mini_cart_product_thumbnail');
        $productName = $this->escaper->escapeHtml($this->item->getProduct()->getName());

        return [
            'options' => $this->getOptionList(),
            'qty' => $this->item->getQty() * 1,
            'item_id' => $this->item->getId(),
            'configure_url' => $this->getConfigureUrl(),
            'is_visible_in_site_visibility' => $this->item->getProduct()->isVisibleInSiteVisibility(),
            'product_id' => $this->item->getProduct()->getId(),
            'product_name' => $productName,
            'product_sku' => $this->item->getProduct()->getSku(),
            'product_url' => $this->getProductUrl(),
            'product_has_url' => $this->hasProductUrl(),
            'product_price' => $this->checkoutHelper->formatPrice($this->item->getCalculationPrice()),
            'product_price_value' => $this->item->getCalculationPrice(),
            'product_image' => [
                'src' => $imageHelper->getUrl(),
                'alt' => $imageHelper->getLabel(),
                'width' => $imageHelper->getWidth(),
                'height' => $imageHelper->getHeight(),
            ],
            'canApplyMsrp' => $this->msrpHelper->isShowBeforeOrderConfirm($this->item->getProduct())
                && $this->msrpHelper->isMinimalPriceLessMsrp($this->item->getProduct()),
            'row_total' => $this->checkoutHelper->formatPrice($this->item->getRowTotal()),
        ];
    }

Display on default template. Add snippet code below to default template (app/design/frontend/my_vendor/my_theme/Magento_Checkout/web/template/minicart/item/default.html)

<div class="row-total" data-bind="html: row_total"></div>

Result: enter image description here

Related Topic