Showing results for 
Search instead for 
Did you mean: 

How to render a layout from a Controller


How to render a layout from a Controller

I am developing a payment method that when it was a fail should run a controller called Failure. When that controller is ran, a page should be displayed to notify the failure of the transaction.

Currently, the controller is being called, but I cannot show the layout yet. This is the execute method of the controller:


* Submit the order
* @return void
* @throws \Magento\Framework\Exception\LocalizedException
public function execute()
if (!$this->getRequest()->isPost()) {

try {
$data = $this->getRequest()->getPostValue();
$tbkIdSession = $data['TBK_ID_SESION'];
$tbkOrdenCompra = $data['TBK_ORDEN_COMPRA'];


$failureBlock = $this->_view->getLayout()->getBlock('checkout.failure');
} catch (\Magento\Framework\Exception\LocalizedException $e) {
} catch (\Exception $e) {
__('We can\'t place the order.')
/** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */
$resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
return $resultRedirect->setPath('checkout/cart'); 


This is the layout definition. The module is called MyModule and the controller folder is called Purchase. The controller class is called Failure.


<?xml version="1.0"?>
* Copyright © 2015 Magento. All rights reserved.
* See COPYING.txt for license details.
<page xmlns:xsi="" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<referenceBlock name="page.main.title">
<action method="setPageTitle">
<argument translate="true" name="title" xsi:type="string">Rejected!</argument>
<referenceContainer name="content">
<block class="Magento\Checkout\Block\Onepage\Failure" name="checkout.failure" template="failure.phtml"/>


The layout definition file is mymodule_purchase_failure.xml and it is actually read, since the page title is set correctly, however, failure.phtml page is not rendered since only a blank page is shown. That phtml file is inside MyModule/view/frontend/templates/onepage. I have added it in onepage folder since the block is controlled by Magento\Checkout\Block\Onepage\Failure, but I have added it in templates folder as well but with no avail.


Any help, please?


Re: How to render a layout from a Controller

Hi Jaime,


i found a good tuto here << Snipped >>

in this part 2  you will find how to render  a layout  with PagFactory class in Controller.

Re: How to render a layout from a Controller

Sorry, but bad practices inside Smiley Sad

Re: How to render a layout from a Controller

1. You should never render layout on POST requests. Only GET requests should render layout. If you want to display error message, do a redirect to error page.


2. To render page you should return ResultPage instance as it's shown in official Magento 2 Code Samples repostiory: