Magento 2 Create View

Follow the below steps to create View.

Step 1: Create controller
Step 2: Create layout file .xml
Step 3: Create block
Step 4. Create template file .phtml

Step 1: Create controller

Firstly, We will create a controller to call the layout file .xml

File: app/code/PHPCodez/First/Controller/Index/Show.php

<?php
namespace PHPCodez\First\Controller\Index;

class Show extends \Magento\Framework\App\Action\Action
{
 protected $_pageFactory;
 public function __construct(
 \Magento\Framework\App\Action\Context $context,
 \Magento\Framework\View\Result\PageFactory $pageFactory)
 {
 $this->_pageFactory = $pageFactory;
 return parent::__construct($context);
 }

public function execute()
 {
 return $this->_pageFactory->create();
 }
}

Step 2: Create layout file .xml

File: app/code/PHPCodez/First/view/frontend/layout/first_index_show.xml

<?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">
 <referenceContainer name="content">
 <block class="PHPCodez\First\Block\Display" name="first_show" template="PHPCodez_First::show.phtml" />
 </referenceContainer>
</page>

In this file, we define the block and template for this page:

Block class: PHPCodez\First\Block\Display

Template file: PHPCodez_First::show.phtml

name: It is the required attribute and is used to identify a block as a reference

Step 3: Create block

The Block file should contain all the view logic required, it should not contain any kind of html or css. Block file are supposed to have all application view logic.

Create a file: app/code/PHPCodez/First/Block/Show.php

<?php
namespace PHPCodez\First\Block;
class Show extends \Magento\Framework\View\Element\Template
{
 public function __construct(\Magento\Framework\View\Element\Template\Context $context)
 {
 parent::__construct($context);
 }

public function welcomeText()
 {
 return __('Welcome to PHPCodez');
 }
}

Every block in Magento 2 should extend from Magento\Framework\View\Element\Template.

Here we have defined a function welcomeText() to display the text ‘Welcome to PHPCodez’ and we will call this function in template.

Step 4. Create template file

Create a template file app/code/PHPCodez/First/view/frontend/templates/show.phtml and insert the following function.

Insert the following code:

<?php
/**
 * @var \PHPCodez\First\Block\Display $block
 */
echo $block->welcomeText();

Now perform php bin/magento setup:static-content:deploy -f and php bin/magento cache:flush and open the URL http://127.0.0.1/mage2/first/index/show

The text ‘Welcome to PHPCodez’ will be displayed on the page.

Leave a Reply

Your email address will not be published. Required fields are marked *