如何在首页Magento 2上显示色板


8

我有两个产品滑块

(基于\Magento\Catalog\Block\Product\Widget\NewWidget)在我的首页上。

我想将色板添加到这些产品滑块。

滑块添加到我的homepage.xml布局中,如下所示:

<container name="items.wrapper.slider" after="full.width.white.bar" htmlTag="div"
           htmlClass="wrapper wrapper--large c-catalog__products--slider-wrapper">
    <block class="Silvan\TestExtension\Block\Product\Widget\NewWidget"
           template="Magento_Catalog::product/widget/new/content/new_grid.phtml" name="new.products">
        <block class="Magento\Swatches\Block\Product\Renderer\Listing\Configurable" as="new.products.swatches" template="Magento_Swatches::product/listing/renderer.phtml" />
    </block>
</container>

我试图通过添加带有类的块来添加色板,Magento\Swatches\Block\Product\Renderer\Listing\Configurable但这不能按预期工作。

有人知道如何在首页中实现这一目标吗?

谢谢。


您想要主页产品中的色板吗?
Rakesh Jesadiya

不,我想在产品系列中显示色板。例如,在Luma主题中,您具有以下概述:dropbox.com/s/yxnwvzobmttkcq3/…。如何添加色板?
user1393817

您可以创建块。在其中插入小部件并选择“小部件类型”:“目录产品列表”和“在条件中”选择您的产品。
Ankit Shah

@ user1393817请检查以下答案以获取产品集中的色板。
Rakesh Jesadiya

@ user1393817,如果您在以下代码中有问题,请告诉我
Rakesh Jesadiya

Answers:


10

在主页中为可配置产品中的显示色板创建简单的模块。

您必须按照以下步骤操作,以获取首页产品系列的样本,

应用程序/代码/测试/Homeslider/registration.php

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Test_Homeslider',
    __DIR__
);

app / code / Test / Homeslider / etc / module.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/Module/etc/module.xsd">
    <module name="Test_Homeslider" setup_version="1.0.0" schema_version="1.0.0">
        <sequence>
            <module name="Magento_Catalog"/>
        </sequence>
    </module>
</config>

app / code / Test / Homeslider / view / frontend / templates / products.phtml

<?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; ?>

创建xml文件以在首页, app / code / Test / Homeslider / 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>

创建文件, app / code / Test / Homeslider / Block / Productslist.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();
    }
}

运行命令,

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

这段代码在@Rakesh上运行良好。感谢那。但是,当我使用带有静态块的phtml文件时,不会显示色板。有什么解决办法吗?
Payal Patel

@PayalPatel,我必须查一下,我还没有检查那种情况。
Rakesh Jesadiya

@RakeshJesadiya,它在首页上工作正常。您能帮我在Magento 2.3的产品页面上在相关产品上添加色板吗?实际上,我已经在相关产品上添加了标签,但是当我选择任何色板时,产品图像都不会改变。
Vinod Kumar,

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.