How to manage cache issue on toplink in mageno 2?
-
21-03-2021 - |
문제
I am showing logged in username in Magento2 toplink. But due to Magento full page cache, it showing another username. I tried using
cachable="false"
for toplink block. It works on the MyDashboard page but it slows down my home page and other cms pages due to its make cachable false for the full page. Anyone, guide me on how to achieve it?
default.xml
<block class="Magento\Framework\View\Element\Template" name="top_link" template="Magento_Theme::html/toplink.phtml" cachable="false"/>
Code for reference(toplink.phtml)
<ul class="top-link">
<?php if ($this->helper('Vendor\ModuleName\Helper\Data')->isLoggedIn()) : ?>
<li><a
href="<?php echo $this->helper('Vendor\ModuleName\Helper\Data')->getBaseUrl('customer/account/logout'); ?>"><?php echo __('Logout'); ?></a>
</li>
<li class="hoverMenu username"><a
class="name"
href="#"
title="<?php echo $this->helper('Vendor\ModuleName\Helper\Data')->getFirstname(); ?>"
><?php echo 'Hi, '.$this->helper('Vendor\ModuleName\Helper\Data')->getFirstname(); ?>
▾</a>
<ul class="subMenu">
<li><a
href="<?php echo $this->helper('Vendor\ModuleName\Helper\Data')->getBaseUrl('customer/account/'); ?>">My
Account</a></li>
<li><a
href="<?php echo $this->helper('Vendor\ModuleName\Helper\Data')->getBaseUrl('returns/rma/list/'); ?>">Return
Order</a></li>
</li>
</ul>
</li>
<?php endif ?>
</ul>
해결책 2
toplink.phtml
<!-- ko if: customer().firstname -->
<li class="hoverMenu username"><a
class="name"
href="#"
data-bind = "attr: {title: customer().firstname}"
>
<!--ko text: new String('<?= $block->escapeHtml(__('Hi, %1', '%1')) ?>').replace('%1', customer().firstname) --><!--/ko-->
</a>
<ul class="subMenu">
<li><a
href="<?php echo $this->helper('Vendor\ModuleName\Helper\Data')->getBaseUrl('customer/account/'); ?>">My
Account</a></li>
<li><a
href="<?php echo $this->helper('Vendor\ModuleName\Helper\Data')->getBaseUrl('returns/rma/list/'); ?>">Return
Order</a></li>
</li>
</ul>
</li>
<!-- /ko -->
Add this script at end of the file:
<script type="text/x-magento-init">
{
"*": {
"Magento_Ui/js/core/app": {
"components": {
"customer": {
"component": "Magento_Customer/js/view/customer"
}
}
}
}
}
</script>
다른 팁
Using knockout
https://github.com/DominicWatts/CustomerLogin/blob/master/view/frontend/templates/index/index.phtml
<!-- ko if: customer().is_logged_in -->
<span class="logged-in"
data-bind="text: new String('<?= $block->escapeHtml(__('Welcome back %1', '%1')) ?>').replace('%1', customer().firstname)">
</span>
<!-- /ko -->
Data comes from plugin
$result['is_logged_in'] = $this->customerSession->isLoggedIn();
제휴하지 않습니다 magento.stackexchange