How load custom layout at frontend from controller in Magento 2

In this article we will learn how to load a custom layout from controller.

So at very first, we will create a layout file which is to be loaded from controller under app/code/VendorName/ModuleName/view/frontend/layout/ , let’s say that frontname_custom_customlayout.xml Write the following code in this file.

<?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="Namespace\Module\Block\Custom" name="custom_layout_load" template="Namespace_Module::custom.phtml" cacheable="false"/>
        </referenceContainer>
    </body>
</page>

Now lets create our Controller Class

<?php
namespace VendorName\ModuleName\Controller\Custom;
 
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;
 
class CustomClass extends Action
{
    /**
     * @var \Magento\Framework\View\Result\PageFactory
     */
    protected $_resultPageFactory;
 
    /**
     * [__construct]
     * @param Context                          $context
     * @param PageFactory                      $resultPageFactory
     */
    public function __construct(
        Context $context,
        PageFactory $resultPageFactory,
    ) {
        $this->_resultPageFactory = $resultPageFactory;
        parent::__construct(
            $context
        );
    }
 
    /**
     * loads custom layout
     *
     * @return \Magento\Framework\View\Result\Page
     */
    public function execute()
    {
       public function execute()
    {
        $resultPage = $this->_resultPageFactory->create();
        if ($this->helper->isModuleEnabled()) {
            $resultPage->addHandle('successpage_onepage_successs'); //loads the layout of successpage_onepage_successs.xml file with its name
       return $resultPage;
             } else {
            $resultPage->addHandle('checkout_onepage_success');
             }
        return $resultPage;
    }
    }
}

That’s all in this article, hope it will help you to load different layout file at frontend.Try the above code and if you have any issue just comment below. 🙂

About Ejaz Alam

A Software Engineer who Believes in a simple lifestyle and follow a simple logic to make himself better than yesterday. :)

View all posts by Ejaz Alam →

Leave a Reply

Your email address will not be published. Required fields are marked *