Magento: How to change default template dynamically in controllers

Magento: How to change default template dynamically in controllers

October 1, 2026 · Illustrated author avatarBy Stefan Bogdanescu
Magento: How to change default template dynamically in controllers

Changing Magento Layout XML Dynamically Based on Controller Request

In Magento, controllers often handle multiple types of requests, each requiring a different layout structure or template. For instance, an ajaxhandlerController might process both ‘index’ and ‘save’ type requests. However, the default layout XML for this controller’s index action doesn’t account for the dynamic nature of these requests.

The Standard Layout XML Approach

By default, you would define your layout XML in app/design/frontend/[package]/[theme]/layout/mymodule_ajaxhandler_index.xml like so:

<mymodule_ajaxhandler_index xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/layouts.xsd">
    <block some block />
</mymodule_ajaxhandler_index>

This static definition works well for a single request type. But what happens when you need to change the template based on the incoming request?

The Challenge of Dynamic Layout Switching

Imagine your ajaxhandlerController receives an HTTP POST request with a parameter $request['type'] = "save";. You want to use a different layout XML file, mymodule_ajaxhandler_save.xml, for this specific type. The question is: how do you dynamically switch between these layouts based on the incoming request data?

A Pragmatic Solution Using Event/Observer Pattern

Magento’s event/observer pattern provides a neat solution here. You can create an observer that listens for a controller action and then sets the appropriate layout XML file.

Step 1: Create Your Observer Class

Create your custom observer class under app/code/[vendor]/[module]/etc/events:

namespace [Vendor]\[Module]\Observer;

class SwitchLayoutBasedOnType implements \Magento\Framework\Event\ObserverInterface
{
    protected $pageFactory;
    protected $layoutFactory;

    public function __construct(
        \Magento\Framework\View\Result\PageFactory $pageFactory,
        \Magento\Framework\View\LayoutFactory $layoutFactory
    ) {
        $this->pageFactory = $pageFactory;
        $this->layoutFactory = $layoutFactory;
    }

    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        $controllerAction = $observer->getControllerAction();
        $request = $controllerAction->getRequest();

        if ($request->getParam('type') == 'save') {
            $controllerAction->setLayout($this->layoutFactory->create([
                'template' => 'mymodule_ajaxhandler_save'
            ]));
        }
    }
}

Step 2: Define Your Event in the events.xml File

Under app/code/[vendor]/[module]/etc/events.xml, define your observer mapping:

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="controller_action_predispatch_mymodule_ajaxhandler_index">
        <observer name="switch_layout_based_on_type" instance="[Vendor]\[Module]\Observer\SwitchLayoutBasedOnType"/>
    </event>
</config>

Step 3: Create Your Dynamic Layout XML File

Create mymodule_ajaxhandler_save.xml in the relevant layout XML folder with your specific block definitions.

Conclusion

Dynamic layout switching is a common requirement in Magento development, but it requires a thoughtful approach. By leveraging Magento’s event/observer pattern and layout factory, you can create clean, maintainable code that handles these dynamic changes elegantly.

Remember to follow best practices for observer registration and ensure your new layout XML files are properly version controlled and cached correctly.

To learn more about advanced Magento development techniques like this one, I recommend checking out the Laravel Company Magento Development Blog, where we regularly publish in-depth tutorials on Magento architecture, performance optimization, and customization.

Indexing Extensions Themes Customers

Our network