我正在尝试为Magento中的特色产品创建产品列表。
我在文件app/code/MyModule/MySite/Block/Products/Featured.php
中编写了以下代码:
<?php
namespace MyModule\MySite\Block\Products;
class Featured extends \Magento\Catalog\Block\Product\ListProduct
{
/**
* Catalog product visibility
*
* @var \Magento\Catalog\Model\Product\Visibility
*/
protected $_catalogProductVisibility;
/**
* Product collection factory
*
* @var \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory
*/
protected $_productCollectionFactory;
/**
* @var CategoryRepositoryInterface
*/
protected $categoryRepository;
public function __construct(
\Magento\Catalog\Block\Product\Context $context,
\Magento\Framework\Data\Helper\PostHelper $postDataHelper,
\Magento\Catalog\Model\Layer\Resolver $layerResolver,
\Magento\Catalog\Api\CategoryRepositoryInterface $categoryRepository,
\Magento\Framework\Url\Helper\Data $urlHelper,
\Magento\Catalog\Model\Product\Visibility $catalogProductVisibility,
\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
array $data = []
) {
$this->_productCollectionFactory = $productCollectionFactory;
$this->_catalogProductVisibility = $catalogProductVisibility;
parent::__construct($context, $postDataHelper, $layerResolver,$categoryRepository,$urlHelper,$data);
}
protected function _getProductCollection(){
$collection = $this->_productCollectionFactory->create()
->addAttributeToFilter('status', '1')
->addAttributeToFilter('featured', '1');
$collection->setVisibility($this->_catalogProductVisibility->getVisibleInCatalogIds());
$collection = $this->_addProductAttributesAndPrices($collection)
->setPageSize(4)
->setCurPage(1);
return $collection;
}
}
在我的页面中,我复制了一行正常工作(第二行是工作代码):
{{block class="MyModule\MySite\Block\Products\Featured" template="WorkingModule_WorkingSite::products/featured_carousel2.phtml" limit="10" category_id="71" block_name="Featured Products"}}
{{block class="Magento\Catalog\Block\Product\ListProduct" template="WorkingModule_WorkingSite::products/featured_carousel2.phtml" limit="10" category_id="71" block_name="Featured Products"}}
第一行没有显示任何内容,当我调试时,getTemplate()
似乎为空。
有人看到我做错了吗?
答案 0 :(得分:0)
如果您只是想在Magento 2中为特色产品创建产品列表,则无需创建自定义模块。很简单。请按照以下步骤操作。
然后使用粘贴下面要添加的代码。
{{block class="Magento\Catalog\Block\Product\ListProduct" template="Magento_Catalog::product/featured_carousel2.phtml" limit="10" category_id="71" block_name="Featured Products"}}