【问题标题】:How to call block functions in phtml file in magento 2?如何在 magento 2 中调用 phtml 文件中的块函数?
【发布时间】:2016-05-22 12:49:13
【问题描述】:

我在 magento 2 中创建自定义模块。我想在 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>

它正在显示 Hello 字样。但不回显上面的代码块

提前谢谢..

【问题讨论】:

  • 你没有提到你正在使用 Magento\Framework\View\Element\Template 的块的主题类,那么它怎么可能

标签: php magento2 magento-2.0


【解决方案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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多