Magento 2 - 空的自定义小部件渲染


Magento 2 - Empty custom widget render

>我尝试在Magento 2 EE上创建自定义小部件,以列出具有自定义属性"end_life"是/否类型的产品。在后台没关系,我创建了类型为"结束寿命产品"的小部件,并将其插入我的主页。

但是主页上的渲染是空的。只是一个<p></p>

请帮助我呈现我的产品列表:)

app/code/my/CustomModule/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="My_CustomModule" setup_version="1.0.0">
    </module>
</config>

app/code/my/CustomModule/etc/widget.xml

<?xml version="1.0" encoding="UTF-8"?>
<widgets xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../Magento/Widget/etc/widget.xsd">
    <widget id="my_custommodule_end_life_products" class="My'CustomModule'Block'Widget'EndLifeProducts">
        <label translate="true">End Life Products</label>
        <description></description>
    </widget>
</widgets>

app/code/My/CustomModule/Block/Widget/EndLifeProducts.php

namespace My'CustomModule'Block'Widget;
class EndLifeProducts extends 'Magento'Framework'View'Element'Template implements 'Magento'Widget'Block'BlockInterface
{
    public function getEndLifeCollection() {
        $objectManager = 'Magento'Framework'App'ObjectManager::getInstance();
        /** @var 'Magento'Catalog'Model'ResourceModel'Product'Collection $productCollection */
        $productCollection = $objectManager->create('Magento'Catalog'Model'ResourceModel'Product'Collection');
        $productCollection->addAttributeToFilter('end_life', true)
            ->load();
        return $productCollection;
    }
    public function _toHtml()
    {
        $this->setTemplate('widget/end_life_products.phtml');
    }
}

app/code/My/CustomModule/view/frontend/widget/end_life_products.phtml

<h1>End Life Products</h1>
<?php
if ($exist = ($block->getEndLifeCollection() && $block->getEndLifeCollection()->getSize())) {
    $items = $block->getEndLifeCollection()->getItems();
}

我找到了一个解决方案:

将模板定义为protected $_template变量,不要定义_toHtml()函数

namespace My'CustomModule'Block'Widget;
class EndLifeProducts extends 'Magento'Framework'View'Element'Template implements 'Magento'Widget'Block'BlockInterface
{
    protected $_template = 'widget/end_life_products.phtml';
    public function getEndLifeCollection() {
        $objectManager = 'Magento'Framework'App'ObjectManager::getInstance();
        /** @var 'Magento'Catalog'Model'ResourceModel'Product'Collection $productCollection */
        $productCollection = $objectManager->create('Magento'Catalog'Model'ResourceModel'Product'Collection');
        $productCollection->addAttributeToFilter('end_life', true)
            ->load();
        return $productCollection;
    }
}

并将您的模板 .phtml 放入您的自定义模块模板文件夹中:app/code/My/CustomModule/view/frontend/template/widget/end_life_products.phtml

文件end_life_products移动到 app/code/My/CustomModule/view/frontend/templates/widget/end_life_products.phtml