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

时间:2016-02-11 16:16:23

标签: php magento2 magento-2.0

我正在使用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 字样。但不回应上面的代码

提前致谢..

1 个答案:

答案 0 :(得分:1)

你应该告诉&#39;你希望传递给内容的阻止你的布局。

<?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>