View our collection in our block template magento2

Magento 2 – Display Collection Data Using Block & Template

This guide is a quick reminder of how Magento 2 MVC works and how we can fetch a collection in a block and render it inside a frontend template. The page URL we use here is:

http://www.example.com/mymodule/test/index

1. Controller Action Execution

When the above URL is accessed, Magento calls the following controller action. This action is responsible for loading and rendering the layout.

<?php namespace Hikmadh\Mymodule\Controller\Test; use Magento\Framework\App\Action\Action; class Index extends Action { public function execute() { $this->_view->loadLayout(); $this->_view->renderLayout(); } }

2. Layout XML Mapping

The controller loads the layout handle mymodule_test_index.xml, which defines which block and template should be rendered on this page.

<?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="Hikmadh\Mymodule\Block\Contactslist" name="contacts.list" template="Hikmadh_Mymodule::test_index.phtml" /> </referenceContainer> </body> </page>

The layout file connects the logical block class with its corresponding template file for rendering the view.

3. Block Class – Fetching the Collection

The block class is responsible for retrieving data. Here, we inject our model and expose a method that returns the collection to the template.

<?php namespace Hikmadh\Mymodule\Block; use Magento\Framework\View\Element\Template; use Hikmadh\Mymodule\Model\Mymodel; class Contactslist extends Template { protected $mymodel; public function __construct( Template\Context $context, Mymodel $mymodel, array $data = [] ) { $this->mymodel = $mymodel; parent::__construct($context, $data); } public function getContacts() { return $this->mymodel->getCollection(); } }

4. Template File – Rendering the Collection

The template accesses the block method and loops through the collection to display the data on the frontend.

<?php $contacts = $block->getContacts(); ?> <div id="contacts-list"> <h3>Contacts List</h3> <?php if ($contacts->getSize()) : ?> <table> <tr> <th>Name</th> <th>Email</th> </tr> <?php foreach ($contacts as $contact) : ?> <tr> <td><?= $block->escapeHtml($contact->getName()); ?></td> <td><?= $block->escapeHtml($contact->getEmail()); ?></td> </tr> <?php endforeach; ?> </table> <?php else : ?> <p>There is no contact in this list.</p> <?php endif; ?> </div>

Final Notes

This pattern cleanly follows Magento 2 MVC: the controller loads the layout, the layout binds blocks and templates, the block handles data, and the template handles rendering.