Magento 2 – Get Product Collection in Custom Template Block

collection;magento2modelproduct-collectiontemplate

I have defined a featured product template in a cms static page as below:

{{block class="Magento\Catalog\Block\Product\ListProduct" template="Magento_Catalog::product/featured.phtml"}}

Now I want to load original product collection(without any filters applied, which I am gonna apply later) inside my template "featured.phtml", but I can't find a way to do it directly without creating a module for such a tiny task.

Somebody let me know, how to do something like below in Magento2, in this case: Mage::getModel('catalog/product')->getCollection()

Best Answer

It is better to create custom block for your needs. It is not clear why you can create custom template, but not block. Also have you considered using \Magento\Catalog\Api\ProductRepositoryInterface::getList which is part of Magento public API? Collection should not be manipulated directly.

Implementation below is a hack (object manager should never be used directly), but the only solution without creation of a new block:

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
/** @var \Magento\Catalog\Model\ResourceModel\Product\Collection $productCollection */
$productCollection = $objectManager->create('Magento\Catalog\Model\ResourceModel\Product\Collection');
/** Apply filters here */
$productCollection->load();