Magento – How in Block a productcollection of template render

magento2productsrenderer

How in Block

app/code/Name/Name/Block/Rewrite/TopMyMenu.php

a productcollection of template

"vendor/magento/module-catalog-widget/view/frontend/templates/product/widget/content/grid.phtml"

render?

$productCollection = $this->categoryFactory->create()->getCollection()
              ->addAttributeToSelect('*')
              ->addAttributeToFilter('is_active', 1)
              ->setOrder('position', 'ASC')
              ->addIdFilter($category->getChildren());

$html = $produCtcollection->toHtml(); ?????

Best Answer

toHtml() return block's html output

Process

\vendor\magento\framework\View\Element\AbstractBlock.php

    public function toHtml()
    {
/* dode */
            $this->_beforeToHtml();
            $html = $this->_toHtml();
            $this->_saveCache($html);
/* dode */
        return $html;
    }

Next this goes to \vendor\magento\framework\View\Element\Template.php

protected function _toHtml()
{
    if (!$this->getTemplate()) {
        return '';
    }
    return $this->fetchView($this->getTemplateFile());
}

Renders block html. and $this->fetchView function retrieves the block view from file (template).

Assume you know templates are using block functions and blocks extends core classes ( Template.php or AbstractBlock.php not in all cases ).

The data is populating by using toHtml()

Hope this helps.