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();
许可以下: CC-BY-SA归因
scroll top