Magento 2 – Custom Header Link Not Showing

headermagento2

I am trying to add custom header link, but it is not showing. For this I am written below code.

Block

<?php

namespace Test\FLinks\Block;

class Header extends \Magento\Framework\View\Element\Html\Link{

    protected $_template = 'Test_FLink::link.phtml';

    public function getHref()
    {
        return __( 'testuser');
    }

    public function getLabel()
    {
        return __('Test Link');
    }

}

layout tried both files default.xml/header.xml

<?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">
            <move element="test-link" destination="header.links"/>
            <block class="Test\FLinks\Block\Header" name="test-link" after="my-account-link"/>
        </referenceBlock>
    </body>
</page>

templates

<?php /** @var  \Test\Flinks\Block\Header $block */ ?>
<li>
    <a <?php echo $block->getLinkAttributes() ?>><?php echo $block->escapeHtml($block->getLabel())?>
        <?php /*echo($block->getCounter()) ? '<span>' . $block->escapeHtml($block->getCounter()) . '</span>' : ''; */?>
        <h1>Welcome to Magento 2</h1>
    </a>
</li>
<h1>Magento 2</h1>

Best Answer

Block File,

<?php

namespace Test\FLinks\Block;

class Header extends \Magento\Framework\View\Element\Html\Link{

    protected $_template = 'Test_FLink::link.phtml';

    public function getHref()
    {
        return $this->getUrl('testuser');
    }

    /**
     * @return \Magento\Framework\Phrase
     */
    public function getLabel()
    {
        return __('Test Link');
    }
}
?>

Template file,

<li class="link testlink">
    <a href="<?php echo $block->getHref() ?>"><?php echo $block->escapeHtml($block->getLabel()) ?>
    </a>
</li>

default.xml file, In xml use top.links for set after my account link,

<?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="top.links">
            <block class="Test\FLinks\Block\Header" name="test-link" after="my-account-link"/>
        </referenceBlock>
    </body>
</page>