Override an existing Magento block template
Sometimes you just need to completely override a template, past what is possible with a translation string. Let’s remove our i18n translations completely to give us the default text back for this wish list sidebar.
When we refresh our page, we’ll see the standard “You have no items in your wish list” message. Let’s add a “Browse for items” link that goes to the home page, in the event no items are in the wishlist. To do this we will need to override this wishlist sidebar block template.
Our first step is to copy the file from the other module into our module. We want to be careful with how these files are named though.
sidebar.phtml file is in the template root of the Wishlist module, let’s go ahead and create a subdirectory under templates named
wishlist. Then within here, we can create our
sidebar.phtml file. If we didn’t do this, this
sidebar.phtml would have some ambiguity to the
post/sidebar.phtml file already in our module.
Next we can copy & paste the contents of the wishlist sidebar over to our new
Then, we can make our changes to this template. Since I already have this coded up, I’m going to paste the link in here to save some time.
... <!-- ko ifnot: wishlist().counter --> <div class="empty"><?= $block->escapeHtml(__('You have no items in your wish list.')) ?></div> <div> <a href="<?= $block->escapeUrl($this->getBaseUrl()) ?>" title="<?= $block->escapeHtmlAttr(__('Browse for items')) ?>"> <span><?= $block->escapeHtml(__('Browse for items')) ?></span> </a> </div> <!-- /ko -->
This just adds a “Browser for items” link to the page.
We created our template file, but Magento doesn’t yet know it exists. So let’s make our template file apply to this blog post detail view by making updates to our
We’ll start by using
referenceBlock again, and then we will reference the name of the original layout XML block. Looking back at
vendor/magento/module-wishlist/view/frontend/layout/default.xml, we know this is
wishlist_sidebar, so the
name attribute of our
referenceBlock container will be
wishlist_sidebar. Now we just need to override the template for this block, so let’s create a new
template attribute and set it to the location of our new template. The value for this will be
Macademy_Blog, followed by two colons, and then
<referenceBlock name="wishlist_sidebar" template="Macademy_Blog::wishlist/sidebar.phtml"/>
Now when we save & refresh our page, the new template will take effect, and our “Browse for items” link will take us to the home page.