Magento 2 Get product collection in a custom template block
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();
Instead of using the Object manager u can try:
public function __construct(
\Magento\Backend\Block\Template\Context $context,
\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
array $data = []
)
{
$this->_productCollectionFactory = $productCollectionFactory;
parent::__construct($context, $data);
}
public function getProductCollection()
{
$collection = $this->_productCollectionFactory->create();
$collection->addAttributeToSelect('*');
$collection->setPageSize(3); // fetching only 3 products
return $collection;
}
In your block file:
use Magento\Catalog\Model\ProductFactory;
use Magento\Framework\View\Element\Template\Context;
protected $_productFactory;
public function __construct(
Context $context,
ProductFactory $productFactory,
array $data = array()
) {
$this->_productFactory = $productFactory;
parent::__construct($context, $data);
}
public function getProductCollection() {
$productCollection = $this->_productFactory->create()->getCollection();
return $productCollection;
}
To get the collection call getProductCollection
function.