简体   繁体   中英

How to call block functions in phtml file in magento 2?

I am creating custom module in magento 2. I want to call block functions in phtml file. But It is not working. Please help me.

Here is my block in adminhtml folder file.

namespace Question\Topic\Block\Adminhtml;

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


    public function getSample() {

             return "abhishek";

    }

}

And my topic_order_view.xml file in view/adminhtml/layout is

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

Here is my controller in 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;

    }
}

my view.phtml file in view/adminhtml/templates/order/view.phtml

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

?>

<h1>Hello </h1>

It is showing the Hello word. But not echo the above block code

Thanks in advance..

You should 'tell' your layout which block you want pass to content.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM