Magento2: how to display small images of product collection data?
-
25-01-2021 - |
Вопрос
how to display small images of product collection data?
Magento 2.0
Решение
Get collection of products in Block
<?php
namespace Vendor\Module\Block;
use Magento\Framework\View\Element\Template;
use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory;
use Magento\Catalog\Helper\Image;
use Magento\Catalog\Model\ProductRepository;
class Products extends Template
{
protected $_productCollectionFactory;
protected $_productImageHelper;
protected $_productRepository;
public function __construct(
Context $context,
CollectionFactory $productCollectionFactory,
Image $productImageHelper,
ProductRepository $productRepository,
)
{
$this->_productCollectionFactory = $productCollectionFactory;
$this->_productImageHelper = $productImageHelper;
$this->_productRepository = $productRepository;
parent::__construct($context);
}
public function getProductBySku($sku)
{
return $this->_productRepository->get($sku);
}
public function resizeImage($product,$imageId, $width, $height = null)
{
$_product = $this->getProductBySku($product->getSku());
$resizedImage = $this->_productImageHelper
->init($_product, $imageId)
->constrainOnly(TRUE)
->keepAspectRatio(TRUE)
->keepTransparency(TRUE)
->keepFrame(FALSE)
->resize($width, $height);
return $resizedImage;
}
public function getProductCollection(){
$collection = $this->_productCollectionFactory->create();
$collection->addAttributeToSelect('*');
$collection->addAttributeToFilter('status',\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED);
$collection->addAttributeToSort('name', 'ASC');
return $collection;
}
}
Call collection in phtml file and display images like below
<?php $productCollection = $block->getCollection(); ?>
<?php foreach ($productCollection as $_product) {
$resizedImageUrl = $block->resizeImage($_product, 'product_base_image', 80, 80)->getUrl(); ?>
echo "<img src=".$resizedImageUrl."/>";
}
?>
Не связан с magento.stackexchange