This website uses cookies

Our website, platform and/or any sub domains use cookies to understand how you use our services, and to improve both your experience and our marketing relevance.

Create a Custom Frontend View in Magento 2

May 31, 2021

3 Min Read

Project structure is one of the most important differences between Magento 1 and Magento 2. To create a custom frontend view in Magento, the developer needs to understand module development, controllers, layouts, blocks, and templates. The process of creating a custom frontend view in Magento 2 is quite similar to the Magento 1.x. The major difference is the very different file structure in Magento 2.

Custom Frontend Magento 2

In this blog, I will create a custom frontend view in Magento 2 and test it on a storefront. For the purpose of this blog, I assume that you have successfully installed Magento 2, either locally or on a web server.

Once Magento 2 is up and running, follow this step-by-step procedure:

  1. Create and Register a New Magento 2 Module
  2. Setup Routing
  3. Controller Action
  4. Layout File
  5. The Block file
  6. Create the Template file
  7. Activate the Module

Create and Register a New Magento 2 Module

Create a new module with Namespace Cloudways and Module name Newmodule. Go to app/code/Cloudways/Newmodule and create a new registration.php file. Add the following code snippet to the file.

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Cloudways_Newmodule',
    __DIR__
);

Next, the module needs to be declared.

Scale Your Magento 2 Store With Ease

One-Click Magento installation with your own managed hosting solution.

For this, create a module.xml file in the app/code/Cloudways/Newmodule/etc and add the following code in it.

<?xml version="1.0"?>
    <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Cloudways_Newmodule" setup_version="1.0.1"></module>
</config>

Setup Routing

The module’s frontend routing information will be reported in routes.xml file. This file should be located in  app/code/Cloudways/Newmodule/etc/frontend and have the following code.

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../lib/internal/Magento/Framework/App/etc/routes.xsd">
    <router id="standard">
        <route id="newmodule" frontName="newmodule">
            <module name="Cloudways_Newmodule" />
        </route>
    </router>
</config>

Controller Action

Create the file Index.php file in app/code/Cloudways/Newmodule/Controller/Index. This will be the controller action and the execute() function in index.php will be invoked when the action is called.

<?php
namespace Cloudways\Newmodule\Controller\Index;
class Index extends \Magento\Framework\App\Action\Action
{
    /** @var  \Magento\Framework\View\Result\Page */
    protected $resultPageFactory;
    /**      * @param \Magento\Framework\App\Action\Context $context      */
    public function __construct(\Magento\Framework\App\Action\Context $context, \Magento\Framework\View\Result\PageFactory $resultPageFactory)
    {
        $this->resultPageFactory = $resultPageFactory;
        parent::__construct($context);
    }
    /**
     * Blog Index, shows a list of recent blog posts.
     *
     * @return \Magento\Framework\View\Result\PageFactory
     */
    public function execute()
    {
        $resultPage = $this->resultPageFactory->create();
        $resultPage->getConfig()->getTitle()->prepend(__('Custom Front View'));
        return $resultPage;
    }
}

Layout File

Layout file in Magento 2 is different from Magento 1’s layout file. Magento 2 uses the layout file inside the module folder, and it is named after the structure of module. A common naming style is  RouterName_ControllerName_ActionName.xml. So in this case, create the file newmodule_index_index.xml in app/code/Cloudways/Newmodule/view/frontend/layout directory. Add the following code to it

<?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 class="Cloudways\Newmodule\Block\Newmodule" name="cloudways_newmodule" template="newmodule.phtml"></block>
        </referenceContainer>
    </body>
</page>

The Block file

The next important step is the creation of the block file for the module. Block file includes several logical function(s) which will be used in the template file. Create a block file in app/code/Cloudways/Newmodule/Block and name it Newmodule.php. Add the following code to it

<?php
namespace Cloudways\Newmodule\Block;
class Newmodule extends \Magento\Framework\View\Element\Template
{
    public function _prepareLayout()
    {
        return parent::_prepareLayout();
    }
}

Create the Template file

The template file will be named newmodule.phtml and will be located in app/code/Cloudways/Newmodule/view/frontend/templates. Once done, add the following code.

<span style="font-weight: 400;">This is custom front view.</span>

Activate the Module

Finally, the module needs to be activated. Open up the SSH Terminal and in the root folder of Magento 2 (i.e. public_html), run the following commands.

rm -rf var/di var/generation var/cache/* var/log/* var/page_cache/*
php bin/magento setup:upgrade
php bin/magento setup:di:compile
php bin/magento cache:clean
php bin/magento cache:flush
php bin/magento indexer:reindex

Congratulations! The Magento 2 custom frontend view has been successfully created. To test it out, run the URL in the following format.

http://yourdomain.com/RouterName/ControllerName/ActionName

In my case, the URL is http://magento-14846-54048-160729.cloudwaysapps.com/newmodule/index/index, and the result is following.

Create a Custom Frontend View Magento 2

Conclusion

The above procedure is the shortest way of creating a custom frontend view in Magento 2. As you could see, Magento 2 offers a much easy way of creating a custom view. If you have a question or would like to contribute to the discussion, leave a comment below.

Share your opinion in the comment section. COMMENT NOW

Share This Article

Customer Review at

“Great speed, features, knowledgebase, dashboard, UX and fast, expert support. Very happy!”

Stefan [Management Consultant]

Fayyaz Khattak

Fayyaz, a passionate Motorbike tourist, works as a Team Lead — Magento Community at Cloudways - A Managed Magento Hosting Platform. His objective is to learn & share about PHP & Magento Development in Community. You can contact him at [email protected]

×

Get Our Newsletter
Be the first to get the latest updates and tutorials.

Thankyou for Subscribing Us!

×

Webinar: How to Get 100% Scores on Core Web Vitals

Join Joe Williams & Aleksandar Savkovic on 29th of March, 2021.

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

x

For 4 Months

Promo: BFCM2021
  • 28

days

  • 28

Hours

  • 28

Mins

  • 28

Secs