Magento2 Custom Block – Loading Admin Layout and Template in a New Page

custom blocklayoutmagento2

I can't get my head wrap around this.

I have this controller

namespace   Vendor\Gift\Controller\Adminhtml\Gift;

use Magento\Backend\App\Action\Context;

class Index extends \Magento\Backend\App\Action
{
    /**
     * @var \Magento\Framework\View\Result\PageFactory
     */
    protected $resultPageFactory;

    /**
     * @param \Magento\Backend\App\Action\Context $context
     */
    public function __construct(
            Context $context
    ) {
        parent::__construct($context);
    }

    public function execute()
    {       
        $resultPage = $this->resultFactory->create(\Magento\Framework\Controller\ResultFactory::TYPE_PAGE);
        return  $resultPage;
    }

}

This layout in view/adminhtml/layout/vendor_gift_index.xml

EDIT:

Changed layout to view/adminhtml/layout/gift_gift_index.xml
after this answer

https://magento.stackexchange.com/a/102800/36102

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <update handle="styles"/>
    <body>
        <referenceContainer name="content">
           <block class="Vendor\Gift\Block\Adminhtml\Gift\Index"  name="vendor.gift.index"  
                    template="Vendor_Gift::gift/index.phtml"  />
        </referenceContainer>
    </body>
</page>

And a template file in:

view/adminhtml/templates/gift/index.phtml

and a block

namespace Vendor\Gift\Block\Adminhtml\Gift;

class Index extends  \Magento\Backend\Block\Template
{
    protected $_template = 'gift/index.phtml';

    public function __construct(
            \Magento\Backend\Block\Template\Context $context
    ) { 
        parent::__construct($context);
    }

    protected function _toHtml() {
        return $this->_template;
    }
}

Why is my output on the page just showing :

Vendor_Gift::gift/index.phtml

instead of the html from the template. Really stuck on this and so close… someone help, please

Best Answer

Your file name needs to be changed like this:

From

vendor_gift_index.xml

To

gift_gift_index.xml

Related Topic