【发布时间】:2019-02-25 17:33:17
【问题描述】:
我正在尝试将 .phtml 文件加载到观察者的模板文件夹中,但出现此错误
无效的模板文件:模块中的“VENDOR_MYModule::Category/index.phtml”:“VENDOR_MYModule”块的名称:“category_0”
这是我的文件结构
app
+ code
+ VENDOR
+ MYModule
+ Block
- Category.php
+ Controller
+ Category
- Index.php
+ etc
+ frontend
- routes.xml
+ Observer
- CategoryObserver.php
+ view
+ frontend
+ layout
- header_category_index.xml
+ templates
+ category
- index.phtml
现在我Block/Category.php的内容如下
<?php
namespace VENDOR\MYModule\Block;
class Category extends \Magento\Framework\View\Element\Template
{
public function __construct(
\Magento\Backend\Block\Template\Context $context,
array $data = []
){
parent::__construct($context, $data);
}
}
我Controller/Category/Index.php的内容如下
<?php
namespace VENDOR\MYModule\Controller\Category;
class Index extends \Magento\Framework\App\Action\Action
{
protected $_pageFactory;
public function __construct(
\Magento\Framework\App\Action\Context $context,
\Magento\Framework\View\Result\PageFactory $pageFactory
)
{
$this->_pageFactory = $pageFactory;
return parent::__construct($context);
}
public function execute()
{
return $this->_pageFactory->create();
}
}
layout/header_category_index.xml的内容如下
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<referenceContainer name="content">
<block class="VENDOR\MYModule\Block\Category" name="category_items" template="VENDOR_MYModule::category/index.phtml" />
</referenceContainer>
</page>
我.phtml的内容只是一个简单的<h1>Hello world</h1>。现在在我的Observer 中,我正在尝试加载这个.phtml 文件,但我无法加载它并收到错误消息。我的观察者Observer\CategoryObserver的内容如下
public function execute(\Magento\Framework\Event\Observer $observer)
{
$layout = $this->_layout->create();
$block = $layout->createBlock('VENDOR\MYModule\Block\Category')->setTemplate('VENDOR_MYModule::Category/index.phtml')->toHtml();
$this->_logger->debug("[DEBUG]::" , [$block]);
}
这是我events.xml的内容
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="catalog_category_save_after">
<observer name="category-edit" instance="VENDOR\MYModule\Observer\CategoryObserver" />
</event>
</config>
但我收到了上述错误。关于如何将此 .phtml 文件加载到观察者的任何想法?我打算将此 .phtml 文件的内容写入 .txt 文件。但我无法继续,因为我尝试输出它,但我仍然收到错误
更新:
使用前端控制器/操作访问尝试了我的代码,并且成功加载了块。现在我认为在 Admin 部分或 Observer 中检索 .phtml 时还有另一种方法或实现。另请注意,当我尝试编辑/保存目录->类别时会触发观察者。
【问题讨论】:
-
我不确定您要满足什么要求,这似乎是一种错误的方法。我建议尝试其他方式来做到这一点。
标签: magento magento2 magento-2.0 magento2.2 magento2.1