How to add custom link with custom html li, class and achor tag in top links after my account link in Magento2
In Magento2, we have seen earlier in my previous post 'How to add custom link in top links after my account link in Magento2' with default html link.
But sometime we needs to add our cutom html tags in link. For example if we want to add a css class in our custom link then we can use the following trick to get it work.
Same as the previous post, consider, we wish to add a 'Test Link' link and assuming custom module name as 'Mynamespace/Mymodule'.
Step 1: Create a block for your custom link app\code\Mynamespace\Mymodule\Block\Link.php then add the code below in your block file.
Code:
Step 2: Now create app\code\Mynamespace\Mymodule\view\frontend\layout\default.xml, if not already created and add code below in body tag
Code:
Step 3: Create a phtml file in path app\code\Mynamespace\Mymodule\view\frontend\templates\link.phtml and add code below or modify the html as per your requirement
Code:
Step 4: Clear All Cache and you are done.
But sometime we needs to add our cutom html tags in link. For example if we want to add a css class in our custom link then we can use the following trick to get it work.
Same as the previous post, consider, we wish to add a 'Test Link' link and assuming custom module name as 'Mynamespace/Mymodule'.
Step 1: Create a block for your custom link app\code\Mynamespace\Mymodule\Block\Link.php then add the code below in your block file.
Code:
<?php
namespace Mynamespace\Mymodule\Block;
class Link extends \Magento\Framework\View\Element\Html\Link
{
protected $_template = 'Mynamespace_Mymodule::link.phtml';
public function getHref()
{
return $this->getUrl('test');
}
public function getLabel()
{
return __('Test Link');
}
}
?>
Step 2: Now create app\code\Mynamespace\Mymodule\view\frontend\layout\default.xml, if not already created and add code below in body tag
Code:
<body>
<referenceBlock name="top.links">
<block class="Mynamespace\Mymodule\Block\Link" name="test-link" after="my-account-link"/>
</referenceBlock>
</body>
Step 3: Create a phtml file in path app\code\Mynamespace\Mymodule\view\frontend\templates\link.phtml and add code below or modify the html as per your requirement
Code:
<li class="Test-Class">
<a <?php echo $block->getLinkAttributes() ?>><?php echo $block->escapeHtml($block->getLabel())?>
<?php echo($block->getCounter()) ? '<span class="counter qty">' . $block->escapeHtml($block->getCounter()) . '</span>' : ''; ?>
</a>
</li>
Step 4: Clear All Cache and you are done.
How to add custom link with custom html li, class and achor tag in top links after my account link in Magento2
Reviewed by Web Technology Funda
on
5:31:00 AM
Rating:
No comments