SPECIAL OFFER: ENJOY 3 MONTHS OF SHOPIFY FOR $1/MONTH SPECIAL OFFER: ENJOY 3 MONTHS OF SHOPIFY FOR $1/MONTH SPECIAL OFFER: ENJOY 3 MONTHS OF SHOPIFY FOR $1/MONTH SPECIAL OFFER: ENJOY 3 MONTHS OF SHOPIFY FOR $1/MONTH SPECIAL OFFER: ENJOY 3 MONTHS OF SHOPIFY FOR $1/MONTH SPECIAL OFFER: ENJOY 3 MONTHS OF SHOPIFY FOR $1/MONTH SPECIAL OFFER: ENJOY 3 MONTHS OF SHOPIFY FOR $1/MONTH SPECIAL OFFER: ENJOY 3 MONTHS OF SHOPIFY FOR $1/MONTH SPECIAL OFFER: ENJOY 3 MONTHS OF SHOPIFY FOR $1/MONTH SPECIAL OFFER: ENJOY 3 MONTHS OF SHOPIFY FOR $1/MONTH

How to display swatches on Magento 2 homepage

Create a simple module to display configurable in-product color swatches on the homepage.

You have to follow the below steps to get a color swatch on the home product gallery,

  1. app/code/Test/house/registration.php
<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Test_Homeslider',
    __DIR__
);

2. application / code / Test / Home / etc / module.xml

<?php
use Magento\Framework\App\Action\Action;

$productCollection = $this->getProductCollection();
$imageBlock =  $block->getLayout()->createBlock('Magento\Catalog\Block\Product\ListProduct');
$showCart = true;
$type = 'widget-new-grid';
$viewMode = 'grid'; 
$image = 'category_page_grid';
$pos = $block->getPositioned();
?>
<div class="title">
    <strong class="newproduct">New Product</strong>
</div>

<div class="products-grid">
    <div id="topseller-slider" class="products list items product-items owlslider" data-jcarousel="true">
        <ul class="product-items" id="topsellerowlslider">
            <?php $iterator = 1; ?>
            <?php foreach ($productCollection as $_product): ?>
            <?php $productImage = $imageBlock->getImage($_product, 'category_page_grid'); 
                if ($pos == null) {                                                        
                    $position = ' style="left:' . $productImage->getWidth() . 'px;'
                        . 'top:' . $productImage->getHeight() . 'px;"';
                }
                ?>
            <?php /* @escapeNotVerified */ echo($iterator++ == 1) ? '<li class="product-item"><div class="product-item-info">' : '</div></li><li class="product-item"><div class="product-item-info">' ?>
            <a href="<?php echo $_product->getProductUrl(); ?>"><?php echo $productImage->toHtml()  ?></a>
            <div class="product details product-item-details">
                <strong class="product name product-item-name">
                <a class="product-item-link"  href="<?php /* @escapeNotVerified */ echo $_product->getProductUrl() ?>">
                <?php /* @escapeNotVerified */ echo $_product->getName(); ?>
                </a>
                </strong>
                <?php if ($showCart): ?>
                <?php echo $this->getProductPricetoHtml($_product, $type); ?>
                <?php echo $block->getProductDetailsHtml($_product); ?>
                <div class="product-item-inner">
                    <div class="product actions product-item-actions">
                        <div class="actions-primary"<?php echo strpos($pos, $viewMode . '-primary') ? $position : ''; ?>>
                            <?php if ($_product->isSaleable()): ?>
                            <?php $postParams = $block->getAddToCartPostParams($_product); ?>
                            <form data-role="tocart-form" action="<?php /* @escapeNotVerified */ echo $postParams['action']; ?>" method="post">
                                <input type="hidden" name="product" value="<?php /* @escapeNotVerified */ echo $postParams['data']['product']; ?>">
                                <input type="hidden" name="<?php /* @escapeNotVerified */ echo Action::PARAM_NAME_URL_ENCODED; ?>" value="<?php /* @escapeNotVerified */ echo $postParams['data'][Action::PARAM_NAME_URL_ENCODED]; ?>">
                                <?php echo $block->getBlockHtml('formkey')?>
                                <button type="submit"
                                    title="<?php echo $block->escapeHtml(__('Add to Cart')); ?>"
                                    class="action tocart primary">
                                <span><?php /* @escapeNotVerified */ echo __('Add to Cart') ?></span>
                                </button>
                            </form>
                            <?php else: ?>
                            <?php if ($_product->getIsSalable()): ?>
                            <div class="stock available"><span><?php /* @escapeNotVerified */ echo __('In stock') ?></span></div>
                            <?php else: ?>
                            <div class="stock unavailable"><span><?php /* @escapeNotVerified */ echo __('Out of stock') ?></span></div>
                            <?php endif; ?>
                            <?php endif; ?>
                        </div>

                        <div class="actions-secondary" data-role="add-to-links">
                            <?php if ($this->helper('Magento\Wishlist\Helper\Data')->isAllow()): ?>
                                <a href="#"
                                   data-post='<?php /* @escapeNotVerified */ echo $block->getAddToWishlistParams($_product); ?>'
                                   class="action towishlist" data-action="add-to-wishlist"
                                   title="<?php /* @escapeNotVerified */ echo __('Add to Wish List') ?>">
                                    <span><?php /* @escapeNotVerified */ echo __('Add to Wish List') ?></span>
                                </a>
                            <?php endif; ?>
                            <?php if ($block->getAddToCompareUrl()) ?>
                                <?php $compareHelper = $this->helper('Magento\Catalog\Helper\Product\Compare');?>
                                <a href="#" class="action tocompare"
                                   data-post='<?php /* @escapeNotVerified */ echo $compareHelper->getPostDataParams($_product);?>'
                                   title="<?php /* @escapeNotVerified */ echo __('Add to Compare') ?>">
                                    <span><?php /* @escapeNotVerified */ echo __('Add to Compare') ?></span>
                                </a>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
            <?php echo($iterator == count($productCollection)+1) ? '</div></li>' : '' ?>
            <?php endforeach ?>
        </ul>
    </div>
</div>
</div>
<?php if (!$block->isRedirectToCartEnabled()) : ?>
<script type="text/x-magento-init">
    {
        "[data-role=tocart-form], .form.map.checkout": {
            "catalogAddToCart": {}
        }
    }
</script>
<?php endif; ?>

generate xml file to display inside homepage, 

3. app/code/Test/Home/view/frontend/layout/cms_index_index.xml

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
      <head>
           <css src="Magento_Swatches::css/swatches.css"/>
    </head> 
    <body>
        <referenceBlock name="homepage.swatchrenderer">
                <block class="Magento\Swatches\Block\Product\Renderer\Listing\Configurable" as="configurable" template="Magento_Swatches::product/listing/renderer.phtml" />
        </referenceBlock>     

        <referenceContainer name="main">
          <container name="topproduct" htmlTag="div" htmlClass="topproduct">
                  <block class="Test\Homeslider\Block\Productslist" name="productlist" template="Test_Homeslider::products.phtml">
                      <block class="Magento\Framework\View\Element\RendererList" name="homepage.swatchrenderer" as="homepage.toprenderers">
                        <block class="Magento\Framework\View\Element\Template" as="default"/>
                      </block>
                  </block>
           </container>
        </referenceContainer>
    </body>
</page>

Create file Block , 

4. application / code / Test / Home / Block / Product.php

<?php
namespace Test\Homeslider\Block;
use Magento\Catalog\Block\Product\ListProduct;
use Magento\Catalog\Model\Category;
use Magento\Catalog\Model\Product;

class Productslist extends \Magento\Framework\View\Element\Template
{   
    protected $_productCollectionFactory;    

    public function __construct(      
        \Magento\Framework\View\Element\Template\Context $context,    
        \Magento\Catalog\Block\Product\Context $gridcontext,  
        \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,       
        \Magento\Catalog\Block\Product\ListProduct $listProductBlock,

        array $data = []
    )
    {   
        $this->_productCollectionFactory = $productCollectionFactory; 
        $this->listProductBlock = $listProductBlock;
        $this->reviewRenderer = $gridcontext->getReviewRenderer();     
        $this->_compareProduct = $gridcontext->getCompareProduct();
        $this->_wishlistHelper = $gridcontext->getWishlistHelper();     
        parent::__construct($context, $data);
    }

    public function isRedirectToCartEnabled()
    {
        return $this->_scopeConfig->getValue(
            'checkout/cart/redirect_to_cart',
            \Magento\Store\Model\ScopeInterface::SCOPE_STORE
        );
    }

    public function getProductDetailsHtml(\Magento\Catalog\Model\Product $product)
    {
        $renderer = $this->getDetailsRenderer($product->getTypeId());
        if ($renderer) {
            $renderer->setProduct($product);
            return $renderer->toHtml();
        }
        return '';
    }

    public function getDetailsRenderer($type = null)
    {
        if ($type === null) {
            $type = 'default';
        }
        $rendererList = $this->getDetailsRendererList();
        if ($rendererList) {
            return $rendererList->getRenderer($type, 'default');
        }
        return null;
    }

    protected function getDetailsRendererList()
    {
        return $this->getDetailsRendererListName() ? $this->getLayout()->getBlock(
            $this->getDetailsRendererListName()
        ) : $this->getChildBlock(
            'homepage.toprenderers'
        );
    }
    public function getProductPricetoHtml(
        \Magento\Catalog\Model\Product $product,
        $priceType = null
    ) {
        $priceRender = $this->getLayout()->getBlock('product.price.render.default');
        $price = '';
        if ($priceRender) {
            $price = $priceRender->render(
                \Magento\Catalog\Pricing\Price\FinalPrice::PRICE_CODE,
                $product
            );
        }
        return $price;
    }
    public function getProductCollection()
    {        
        $collection = $this->_productCollectionFactory->create();
        $collection->addAttributeToFilter('type_id', 'configurable');
        $collection->addAttributeToFilter('visibility', \Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH);
        $collection->addAttributeToFilter('status',\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED);
        $collection->setPageSize(10); 
        $collection->addAttributeToSelect('*');
        return $collection;
    }

    public function getAddToCartPostParams($product)
    {
        return $this->listProductBlock->getAddToCartPostParams($product);
    }

    public function getAddToWishlistParams($product)
    {
        return $this->_wishlistHelper->getAddParams($product);
    }
    public function getAddToCompareUrl()
    {
        return $this->_compareProduct->getAddUrl();
    }
}

Run command,

php bin/magento setup:upgrade
php bin/magento setup:static-content:deploy

Hope this article will help you in some way, You can see useful articles in the next articles.

Anything you need support from Magento 2 feels free to contact us at Alothemes and

Phone: (+84)865633728

Email: support@alothemes.com