Menu Close
    Searching for an experienced Magento 2 Development Company ?

    Add Custom Block and Link Header in Magento 2

    In this article, we will learn how to call a custom link and block in the header in Magento 2.

    So, the file (default.xml) is used to define configurations of the header.This file will be located under app/code/Namespace/Module/view/frontend/layout/. This file calls on every page, that’s why we write code for the header in this file.

    <?xml version="1.0"?>
    <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
         <referenceBlock name="header.links">
           <block class="Magento\Framework\View\Element\Html\Link" name="webkul-top-link">
             <arguments>
               <argument name="label" xsi:type="string" translate="true">Test Link</argument>
               <argument name="path" xsi:type="string">test/test</argument>
             </arguments>
           </block>
         </referenceBlock>
    </body>
    </page>

    Now If you want to add your own custom block inside the header,
    then below code will be used :

    <?xml version="1.0"?>
    <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
         <referenceBlock name="header.links">
           <block class="Webkul\Test\Block\Link" name="webkul-top-link">
             <arguments>
               <argument name="label" xsi:type="string" translate="true">Test Link</argument>
               <argument name="path" xsi:type="string">test/test</argument>
             </arguments>
           </block>
         </referenceBlock>
    </body>
    </page>

    Now, create Link.php at location app/code/Webkul/Test/Block and add the below code.

    <?php
     
    namespace Webkul\Test\Block;
     
    class Link extends \Magento\Framework\View\Element\Html\Link
    {
      /**
       * Render block HTML.
       *
       * @return string
      */
      protected function _toHtml() {
        if (false != $this->getTemplate()) {
          return parent::_toHtml();
        }
        $label = $this->escapeHtml($this->getLabel());
        return '<li><a ' . $this->getLinkAttributes() . ' >' . $label . '</a></li>';
    
      }
    }

    Now flush the cache of the Magento by running the below command:
    php bin/magento cache:flush

    You will see the top link on your store like below.

    In this way, you can create custom top links.
    Hope it will help you. Thank you.

    . . .
    Discuss on Helpdesk

    Leave a Comment

    Your email address will not be published. Required fields are marked*


    Be the first to comment.

    Back to Top