提问者:小点点

如何在Magento2中调用phtml文件中的块函数?


我正在Magento2中创建自定义模块。我想在phtml文件中调用块函数。但这并不奏效。请帮帮我.

这是我在adminhtml文件夹文件中的块。

namespace Question\Topic\Block\Adminhtml;

class Topic extends  \Magento\Framework\View\Element\Template {


    public function getSample() {

             return "abhishek";

    }

}

view/adminHTML/layout中的topic_order_view.xml文件是

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../../lib/internal/Magento/Framework/View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="content">
            <block class="Magento\Framework\View\Element\Template" name="view" template="Questions_Topic::view.phtml" />
        </referenceContainer>
    </body>
</page>

下面是我的控制器,位于controller/adminHTML/order/view.php中--

namespace Question\Topic\Controller\Adminhtml\Order;

use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;
use Magento\Framework\App\Config\ScopeConfigInterface;

class View extends \Magento\Backend\App\Action
{

    /**
     * @var PageFactory
     */
     protected $resultPageFactory;
    /**
     * @var scopeConfig
     * Needed to retrieve config values
     */
    protected $scopeConfig;



   public function __construct(
        Context $context,
        PageFactory $resultPageFactory,
        ScopeConfigInterface $scopeConfig // Needed to retrieve config values
    ) {
        parent::__construct($context);
        $this->resultPageFactory = $resultPageFactory;
        $this->scopeConfig = $scopeConfig; // Needed to retrieve config values
    }

      public function execute()
    {
        $resultPage = $this->resultPageFactory->create();

        $resultPage->getConfig()->getTitle()->prepend(__('Orders')); // 

         return $resultPage;

    }
}

view/adminHTML/templates/order/view.phtml中的我的view.phtml文件

<?php
//echo $this->getSample();
echo $block->getSample();

?>

<h1>Hello </h1>

显示的是“你好”字。但不回显上述分组码

事先谢谢..


共1个答案

匿名用户

您应该“告诉”您的布局您想要传递给内容的块。

<?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">
    <body>
        <referenceContainer name="content">
            <block class="Question\Topic\Block\Adminhtml\Topic" name="question.topic.view" template="Questions_Topic::view.phtml" />
        </referenceContainer>
    </body>
</page>