Magento 2 View Layer - Paul Meștereagă
Magento 2

View Layer in Magento 2

In this tutorial I will give an overview of the Magento 2 View Layer. We will learn how to build Blocks, Templates and Layouts.

author

Paul Mestereaga

June 7, 2018

In this tutorial I will give an overview of the Magento 2 View Layer. We will learn how to build Blocks, Templates and Layouts.

I will use the previous tutorials as a base. You can check my previous posts about Magento 2.

Blocks

The location to put the Block classes is inside the Block folder into your module folder. Bellow is an example of a Block class, defined in the Block\Hello.php file.

<?php
namespace Mesteru\FirstModule\Block;
 
use Magento\Framework\View\Element\Template;
use Mesteru\FirstModule\Model\ResourceModel\Item\Collection;
use Mesteru\FirstModule\Model\ResourceModel\Item\CollectionFactory;
 
class Hello extends Template
{
    private $collectionFactory;
 
    public function __construct(
        Template\Context $context,
        CollectionFactory $collectionFactory,
        array $data = []
    ) {
        $this->collectionFactory = $collectionFactory;
        parent::__construct($context, $data);
    }
 
    /**
     * @return \Mesteru\FirstModule\Model\Item[]
     */
    public function getItems()
    {
        return $this->collectionFactory->create()->getItems();
    }
}

In this class we want to use our Item collection. To do that we make use of the dependency injection to add the $collectionFactory through the constructor. Magento 2 will generate the CollectionFactory class if we just specify it as in the example use Mesteru\FirstModule\Model\ResourceModel\Item\CollectionFactory;.

The method getItems will return our items for the template. When we call $this->collectionFactory->create() it will create a new instace of Mesteru\FirstModule\Model\ResourceModel\Item\Collection for us.

Templates

Let’s create a template for our Block. Frontend templates are located in view\frontent\templates. Here we create the hello.phtml template file.

<?php /** @var \Mesteru\FirstModule\Block\Hello $block */ ?>
<ul>
<?php foreach ($block->getItems() as $item): ?>
   <li>
    <?php echo $item->getName(); ?>
   </li>
<?php endforeach; ?>

In this template file we just display a list of our Items.

Layouts

Finaly we have to create a layout to tell Magento where to display or template. Layouts in Magento 2 are stored in frontend\layout\ inside our module. Here we create an xml file that has the name according to our route. In our case we use mesteru_index_index.xml.

First part of the file name is the frontName of the route defined in the etc\frontend\routes.xml which is mesteru, the second part comes from the controller name which is index and the third part comes from the action of the controller which is the also index. Here is the file content:

<!?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 name="mesteru_hello" class="Mesteru\FirstModule\Block\Hello" template="hello.phtml">
        </block></referencecontainer>
</page>

In this file we define where the block to be rendered. Also we specify the block type and the template.

In the previous tutorial about controllers we created Mesteru\FirstModule\Controller\Index\Index.php. We need to adapt the action to render our layout. For this purpose we change the content of the execute() method as follows:

public function execute()
{
   return $this->resultFactory->create(ResultFactory::TYPE_PAGE);
}

Now let’s flush the caches:

php bin/magento cache:flush

Go into the browser and navigate to yourmagento.com/mesteru to access the frontend controller.

Conclusion

Now you know how to create Views in Magento 2 and how Magento 2 View Layer works. If you have any question don’t hesitate to leave a message in the comments section bellow.

Get the Code

You can get the complete code on my github profile here.

Magento 2 from Zero to Beginner Free Online Course

In 10 hours you will have all the basic knowledge so that you could develop your modules without wandering around how to implement stuff.

Related Posts

Magento checkout optimization

15 Dec 2022

|

Paul Mestereaga

Optimizing the checkout process on your Magento eCommerce website is essential for increasing conversions and improving customer satisfaction. A seamless checkout experience can make all the difference in the success of your online store.

3 Things That Kill Your Magento Store’s Conversion Rate

10 Dec 2021

|

Paul Mestereaga

The store receives a lot of traffic, and you market to the right audience. The brand is actively promoted on social media and succeeds in SEO, so the marketing efforts appear to be working.
But what if it doesn’t lead to many sales?

optimize-magento-preview

FREE!

Magento 2
Optimization guide

Wondered how you can make your Magento load faster? Wonder no more. Here is a step by step guide that helps you.