Magento2 customer account navigation wishlist Items how to display in phtml
-
01-10-2020 - |
Question
In app\code\Magento\Wishlist\view\frontend\layout\default.xml
file,I find the block
<referenceBlock name="top.links">
<block class="Magento\Wishlist\Block\Link" name="wish-list-link" after="my-account-link"/>
</referenceBlock>
And in app\code\Magento\Wishlist\Block\Link.php
Specifies the template file
protected $_template = 'Magento_Wishlist::link.phtml';
So I open app\code\Magento\Wishlist\view\frontend\templates\link.phtml
<li class="link wishlist" data-bind="scope: 'wishlist'">
<a <?php /* @escapeNotVerified */ echo $block->getLinkAttributes() ?>><?php echo $block->escapeHtml($block->getLabel()) ?>
<!-- ko if: wishlist().counter -->
<span data-bind="text: wishlist().counter" class="counter qty"></span>
<!-- /ko -->
</a>
</li>
<script type="text/x-magento-init">
{
"*": {
"Magento_Ui/js/core/app": {
"components": {
"wishlist": {
"component": "Magento_Wishlist/js/view/wishlist"
}
}
}
}
}
It looks like using knockoutjs.
This page app\code\Magento\Wishlist\view\frontend\web\js\view\wishlist.js
and file app\code\Magento\Customer\view\frontend\web\js\customer-data.js
But I still do not understand,JavaScript is how to get the number wishlist.
data-bind="text: wishlist().counter"
Solution
inside wishlist module, link.phtml file,
<span data-bind="text: wishlist().counter" class="counter qty"></span>
<script type="text/x-magento-init">
{
"*": {
"Magento_Ui/js/core/app": {
"components": {
"wishlist": {
"component": "Magento_Wishlist/js/view/wishlist"
}
}
}
}
}
</script>
This file is called: magento2/vendor/magento/module-wishlist/view/frontend/web/js/view/wishlist.js
Inside this file you can check,
this.wishlist = customerData.get('wishlist');
Here wishlist is passed into magento2/vendor/magento/module-customer/view/frontend/web/js/customer-data.js
In customer-data.js file you can check get() method call,
Here sectionName is passed as wishlist,
get: function (sectionName) {
return buffer.get(sectionName);
},
above file called your modules CustomerData/Wishlist.php
file,
Now you can check in magento2/vendor/magento/module-wishlist/CustomerData/Wishlist.php file,
public function getSectionData()
{
$counter = $this->getCounter();
return [
'counter' => $counter,
'items' => $counter ? $this->getItems() : [],
];
}
So you can access counter as wishlist().counter and wishlist items as wishlist().items using knockout js.
for wishlist().items access in,
/vendor/magento/module-wishlist/view/frontend/templates/sidebar.phtml
you can check call,
<ol class="product-items no-display" id="wishlist-sidebar" data-bind="foreach: wishlist().items, css: {'no-display': null}"></ol>
Here is same concept.
OTHER TIPS
Check following file:
Magento/Wishlist/CustomerData/Wishlist.php
public function getSectionData()
{
$counter = $this->getCounter();
return [
'counter' => $counter,
'items' => $counter ? $this->getItems() : [],
];
}
wishlist().counter
return php counter.