Magento 2 call list.phtml with custom collection
-
28-02-2021 - |
Вопрос
I have custom collection in $collection
I want to pass it to list.phtml
so that I don't have to create listing UI again. I am trying to do this but it is not working
<?php
echo $this->getLayout()
->createBlock("Magento\Catalog\Block\Product\ListProduct")
->setProductCollection($collection)
->setTemplate("Magento_Catalog::product/list.phtml")
->toHtml();
?>
Решение
This was possible in Magento 1.9 to pass product collection to list.phtml, but you cannot do this in Magento 2.
The proper way to do this is to create your own Block file
app/code/Vendor/Module/Block/ProductList.php
Code will be:
<?php
namespace Vendor\Module\Block;
class ProductList extends \Magento\Catalog\Block\Product\ListProduct
{
protected function _getProductCollection()
{
if ($this->_productCollection === null) {
//Generate your collection here
$this->_productCollection = $collection;
}
return $this->_productCollection;
}
}
Now call list.phtml using your custom Block
echo $this->getLayout()
->createBlock("Vendor\Module\Block\ProductList")
->setTemplate("Magento_Catalog::product/list.phtml")
->toHtml();
Не связан с magento.stackexchange