Magento 2 - Call list phtml by passing collection variable
First you need to create block Vendor\Module\Block\ProductList.php
by overriding this function _getProductCollection()
by extending your class from this Magento\Catalog\Block\Product\ListProduct
.
protected function _getProductCollection()
{
/* Do whatever you want to do with your collection */
$this->_productCollection = $yourcollection;
return $this->_productCollection;
}
Now you can call your ptml
file. Your collection has been passed to that phtml
$block = $viewBlock->getLayout()
->createBlock('Vendor\Module\Block\ProductList')
->setTemplate('Magento_Catalog::product/list.phtml')
->toHtml();
I hope this will help others
try this way....
$block = $viewBlock->getLayout()
->createBlock('Vendor\Module\Block\ProductList')
->setCustomvalue('111111')
->setTemplate('Magento_Catalog::product/list.phtml')
->toHtml();
and you can get value
$block->getCustomvalue();
Your $block
variable contains the content of list.phtml
so here you just have called it.
That list.phtml
contains $_productCollection
that it gets it from the module block
, in your $block
you can do anything in that collection because the collection has already been loaded, it's too late to update it at this level.
What you can to do is to rewrite that block Magento_Catalog\Block\Product\ListProduct.php
and after that, you can update the collection.