How to call template from a Controller in Magento 2?

How to call template from a Controller in Magento 2_

Controllers in Magento 2, like on other PHP MVC frameworks, are important part of MVC flow. In Magento 2 controllers have only one method (execute) that will be called by front controller. It functionality is that received request, process and render page. In Magento 2 Controller has one or more files in Controller folder of module, it includes actions of class which contain execute() method.

There are 2 different controllers, they are frontend controller and backend controller.

Difference between admin and front controller : Main difference between these two controllers is in additional check and additional methods in admin controller. Both controllers eventually extend \Magento\Framework\App\Action\Action class, but admin controller extend \Magento\Backend\App\Action class, which extends \Magento\Framework\App\Action\Action. Both are generally similar of workflow, but admin controller is a little different. There is a checking permission method in admin controller, it calls form key.

You can call template file from a controller. Follow the below steps.

Step 1 : Create controller file

File Path : app/code/V4U/Helloworld/Controller/Index/View.php

Step 2: Create Block file

File Path : app/code/V4U/Helloworld/Block/View.php

Step 3: Create template file

File Path : app/code/V4U/Helloworld/view/frontend/templates/view.phtml

Step 4: Run the following Magento commands :

php bin/magento setup:upgrade

php bin/magento setup:static-content:deploy -f

php bin/magento cache:clean

Step 7: Launch the url :

Ex :

For More Info download this module.

🙂 Happy Coding. Keep Liking & Sharing 💻

Tagged , ,