how to add remove header links conditionally. I am trying to show my account link only when the customer is logged in. Otherwise it should be hidden. How to do the same using xml files.
-
For that use plugin– Nikhil VaghelaCommented Mar 1, 2017 at 10:09
-
@NikhilVaghela, which plugin, please suggest name.– Amit DwivediCommented Mar 1, 2017 at 10:10
-
@NikhilVaghela : So, do you mean it cannot be done using xml, because I am trying to achieve this by making modifications in theme– Pankaj BhopeCommented Mar 1, 2017 at 10:10
-
check my update ans., it's working– Nikhil VaghelaCommented Mar 1, 2017 at 10:52
Add a comment
|
1 Answer
events.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="layout_load_before">
<observer name="vendor_test_layout_load_before" instance="Vendor\Test\Observer\LayoutLoadBefore" />
</event>
</config>
app/code/Vendor/Test/Observer/LayoutLoadBefore.php
<?php
namespace Vendor\Test\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\App\Filesystem\DirectoryList;
class LayoutLoadBefore implements ObserverInterface
{
public function execute(\Magento\Framework\Event\Observer $observer)
{
// add your condition here
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$httpContext=$objectManager->get('Magento\Framework\App\Http\Context');
$isLoggedIn=$httpContext->getValue(\Magento\Customer\Model\Context::CONTEXT_AUTH);
if(!$isLoggedIn){
$layout = $observer->getData('layout');
$layout->getUpdate()->addUpdate('<body>
<referenceBlock name="top.links">
<referenceBlock name="register-link" remove="true" />
</referenceBlock>
</body>');
}
// condition over here
return $this;
}
}