View Modal (CategoryList.php)
use Magento\Catalog\Model\Category;
use Magento\Catalog\Model\ResourceModel\Category\CollectionFactory;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\View\Element\Block\ArgumentInterface;
class CategoryList implements ArgumentInterface
{
/**
* @var CollectionFactory
*/
private $categoryFactory;
/**
* @var Category
*/
private $category;
public function __construct(
CollectionFactory $categoryFactory,
Category $category
) {
$this->categoryFactory = $categoryFactory;
$this->category = $category;
}
/**
* @return array
*/
public function getList()
{
$collection = $this->categoryFactory->create();
$items = [];
$collection->addFieldToFilter('is_active', ['eq' => 1]);
foreach ($collection as $key => $categoryData) {
/** @var \Magento\Catalog\Model\Category $category */
try {
$category = $this->category->load($categoryData->getID());
$items[$key]['image'] = $category->getImageUrl();
$items[$key]['name'] = $category->getName();
} catch (LocalizedException $e) {
}
}
return $items;
}
}
in your_layout.xml file
<block class="Magento\Framework\View\Element\Template" template="Vendor_Module::template.phtml">
<arguments>
<argument name="category_list" xsi:type="object">\Ktpl\CategoryCms\ViewModel\CategoryList</argument>
</arguments>
</block>
in your template.phtml file
<?php
/** @var $viewModel \Ktpl\CategoryCms\ViewModel\CategoryList */
$viewModel = $block->getCategoryList();
$categories = $viewModel->getList();
?>
<div class="home-cat-wrap">
<div class="category">
<?php foreach ($categories as $category): ?>
<div class="cat-item">
<div class="cat-img">
<img src="<?= $category['image'] ? $category['image'] : "http://demo.link" ?>" alt="">
</div>
<h4><a href="#"><?= $category['name'] ?></a></h4>
</div>
<?php endforeach; ?>
</div>
<div class="view-more"><a class="action primary">View More Categories</a></div>
</div>