How To

How to Set a Theme on a Specific Page in Magento 2?

Hello Magento Friends,

In this blog, I will explain the steps to Set a Theme on a Specific Page in Magento 2. 

Magento 2 allows you to set a global theme for your entire store. But there might be cases where you want to apply a different theme to a specific page. This could be for promotional campaigns, seasonal changes, or any other reason.

Let’s go through the process of setting a theme on a specific page in Magento 2.

Steps to Set a Theme on a Specific Page in Magento 2:

Step 1: Create a routes.xml file in the path given below

{{magento_root}}\app\code\Vendor\Extension\etc\frontend\routes.xml

Then add the code as follows.

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
    <router id="standard">
        <route id="frontroute" frontName="frontroute">
            <module name="Vendor_Extension"/>
        </route>
    </router>
</config>

Step 2: Create a controller file in the following path

{{magento_root}}\app\code\Vendor\Extension\Controller\Index\Index.php

Then add the code as given below.

<?php

namespace Vendor\Extension\Controller\Index;

use Magento\Framework\App\Action\HttpGetActionInterface;
use Magento\Framework\Controller\ResultInterface;
use Magento\Framework\View\Result\PageFactory;

class Index implements HttpGetActionInterface
{
    /**
     * @var PageFactory
     */    protected $resultPageFactory;

    /**
     * Constructor
     *
     * @param PageFactory $resultPageFactory
     */    public function __construct(PageFactory $resultPageFactory)
    {
        $this->resultPageFactory = $resultPageFactory;
    }

    /**
     * Execute view action
     *
     * @return ResultInterface
     */    public function execute()
    {
        return $this->resultPageFactory->create();
    }
}

Step 3: Create a layout file at the below-mentioned path

{{magento_root}}\app\code\Vendor\Extension\view\frontend\layout\frontroute_index_index.xml

Add the following code-snippet

<?xml version="1.0" ?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="content">
            <block name="index.index" class="Vendor\Extension\Block\Index\Index" template="Vendor_Extension::index/index.phtml"/>
        </referenceContainer>
    </body>
</page>

Step 4: Create a template file at the path mentioned below

{{magento_root}}\app\code\Vendor\Extension\view\frontend\templates\index\index.phtml

Now, add the code as given below.

<?php
/**
 *
 * @var $block \Vendor\Extension\Block\Index\Index
 */?>

<h2>This page is Magento Black theme.</h2>

Step 5: Create a Block file at the below path

{{magento_root}}\app\code\Vendor\Extension\Block\Index\Index.php

Then add the below-mentioned piece of code.

<?php

namespace Vendor\Extension\Block\Index;

class Index extends \Magento\Framework\View\Element\Template
{
    /**
     * Constructor
     *
     * @param \Magento\Framework\View\Element\Template\Context  $context
     * @param array $data
     */    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        array $data = []
    ) {
        parent::__construct($context, $data);
    }
}

Step 6: Create an events file at the following path

{{magento_root}}\app\code\Vendor\Extension\etc\events.xml 

Then, include the code as follows.

<?xml version="1.0" encoding="UTF-8"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="layout_load_before">
        <observer name="observer_name" instance="Vendor\Extension\Observer\SetThemePage"/>
    </event>
</config>

Step 7: Create an observer class file at the following path

{{magento_root}}\app\code\Vendor\Extension\Observer\SetThemePage.php

And the below-mentioned code

<?php 

namespace Vendor\Extension\Observer;

use Magento\Framework\App\Request\Http;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\View\DesignInterface;

class SetThemePage implements ObserverInterface
{
    /** @var Http */    private Http $request;

    /** @var DesignInterface  */    private DesignInterface $design;

    /**
     * @param Http $request
     * @param DesignInterface $design
     */    public function __construct(
        Http $request,
        DesignInterface $design
    ) {
        $this->request = $request;
        $this->design = $design;
    }

    /**
     * @param Observer $observer
     */    public function execute(Observer $observer): void
    {
        $pathInfo = $this->request->getPathInfo();
        if (substr($pathInfo, 0, 8) === '/frontroute') {
            $this->design->setDesignTheme('Magento/blank');
        }
    }
}

Step 8: Finally, run the below commands.

php bin/magento setup:upgrade 
php bin/magento setup:static-content:deploy -f
php bin/magento setup:di:compile
php bin/magento cache:flush

Conclusion:

Setting a theme on a specific page in Magento 2 is a powerful way to create unique experiences for your customers. By following the steps outlined in this blog post, you can effectively apply different themes to specific pages and enhance the visual appeal and functionality of your Magento 2 store.

You may also like to check out below blogs –

How to Apply Admin Theme in Magento 2?

How to Create Child Theme in Magento 2

Easy Method to Apply The Default Theme In Magento 2

How to Change Theme In Magento 2

If you face any difficulty or errors while executing the above steps, kindly let me know through the comment box, and I will quickly help you out to get rid of the error. Share the tutorial to set a theme for a specific page in Magento 2 with your friends, and stay in touch with us.

Happy Coding!

Click to rate this post!
[Total: 0 Average: 0]
Dhiren Vasoya

Dhiren Vasoya is a Director and Co-founder at MageComp, Passionate 🎖️ Certified Magento Developer👨‍💻. He has more than 9 years of experience in Magento Development and completed 850+ projects to solve the most important E-commerce challenges. He is fond❤️ of coding and if he is not busy developing then you can find him at the cricket ground, hitting boundaries.🏏

Recent Posts

React Native or Flutter in 2024

The mobile app development field has witnessed a rapid revolution over the past few years.…

14 hours ago

Magento 2: How To Call JS on the Checkout Page?

Hello Magento mates, Today we will learn to add a call JS on the checkout…

4 days ago

Boost Your SEM Game: Unveiling the Top 10 Tools for Marketers in 2024

Business survival in today’s digital world has become extremely difficult. Using traditional marketing techniques is…

5 days ago

Five Essential Payroll Compliance Tips for eCommerce Startups

Are you setting up a payroll system for your eCommerce startup? Ensuring compliance with myriad…

6 days ago

Optimizing Laravel Blade: Unlocking Advanced Fetcher Techniques

In the expansive universe of Laravel development, Blade serves as the stellar templating engine, propelling…

6 days ago

Magento 2: Add Quantity Increment and Decrement on Category Page

Hello Magento Friends, In this blog, we will discuss about adding quantity increment and decrement…

1 week ago