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

Magento 2 - Empty custom widget render

我尝试在 Magento 2 EE 上创建自定义小部件以列出具有自定义属性 'end_life' Yes/No 类型的产品。 在后台没问题,我创建了 "End Life Products" 类型的小部件,并将其插入我的主页。

但是主页上的渲染是空的。只是一个<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.phtml 移动到 app/code/My/CustomModule/view/frontend/templates/widget/end_life_products.phtml