Magento 2: Examples About Blocks and Templates

This tutorial shows you some examples about how to use Magento 2 Blocks, Layout, and templates

Posted on August 30, 2017 in Magento

Create a new Magento 2 Module, called ‘Jeff_Office’

registration.php file


#app/code/Jeff/Office/registration.php

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

module.xml file


#app/code/Jeff/Office/etc/module.xml

<?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="Jeff_Office" setup_version="0.0.3">
        <sequence>
            <module name="Mgaento_Eav" />
        </sequence>
    </module>
</config>

frontend routes.xml


#app/code/Jeff/Office/etc/frontend

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
    <router id="standard">
        <route id="jeff_office" frontName="jeff_office">
            <module name="Jeff_Office"/>
        </route>
    </router>
</config>

Index.php controller action file


#app/code/Jeff/Office/Controller/Index/Index.php

<?php
namespace Jeff\Office\Controller\Index;
class Index extends \Magento\Framework\App\Action\Action
{

    protected $resultPageFactory;
    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Framework\View\Result\PageFactory $resultPageFactory)
    {
        $this->resultPageFactory = $resultPageFactory;        
        parent::__construct($context);
    }
    
    public function execute()
    {
        $resultPage = $this->resultPageFactory->create();
        
        //Text Block Examples
        $block = $resultPage->getLayout()->createBlock(
            'Magento\Framework\View\Element\Text',
            'example_1'
        )->setText(
            '<p>Text_1 This is a text this is a text this is a text.</p>'
        );

        $resultPage->getLayout()->setChild(
            'content',
            $block->getNameInLayout(),
            'exmaple_1_alias'
        );

        //ListText Block examples
        $blockT = $resultPage->getLayout()->createBlock(
            'Magento\Framework\View\Element\Text\ListText',
            'example_2'
        );

        $resultPage->getLayout()->setChild(
            'content',
            $blockT->getNameInLayout(),
            'example_2_alias'
        );

        $block2A = $resultPage->getLayout()->createBlock(
            'Magento\Framework\View\Element\Text',
            'example_2a'
        )->setText(
            '<p>Text_2A: First Text block </p>'
        );

        $resultPage->getLayout()->setChild(
            'example_2',
            $block2A->getNameInLayout(),
            'example_2a_alias'
        );

        $block2B = $resultPage->getLayout()->createBlock(
            'Magento\Framework\View\Element\Text',
            'example_2b'
        )->setText(
            '<p>Text_2B: Second Text Block</p>'
        );

        $resultPage->getLayout()->setChild(
            'example_2', //the parent block name
            $block2B->getNameInLayout(), //the child block name
            'example_2b_alias'
        );

        //Message Block Examples
        $messageBlock = $resultPage->getLayout()->createBlock(
            'Magento\Framework\View\Element\Messages',
            'example_3'
        );
        
        $messageBlock->addSuccess('Text_3A: Success');
        $messageBlock->addNotice('Text_3B: Notice');
        $messageBlock->addWarning('Text_3C: Warning');
        $messageBlock->addError('Text_3D: Error');

        $resultPage->getLayout()->setChild(
            'content',
            $messageBlock->getNameInLayout(),
            'example_3_alias'
        );

        //Template Block examples
        $templateBlock = $resultPage->getLayout()->createBlock(
            'Magento\Framework\View\Element\Template',
            'example_templateblock'
        )->setTemplate(
            'Jeff_Office::office/no4/example.phtml'
        );

        $resultPage->getLayout()->setChild(
            'content',
            $templateBlock->getNameInLayout(),
            'example_4_alias'
        );

        //Custom Block Examples
        $customBlock = $resultPage->getLayout()->createBlock(
            'Jeff\Office\Block\Main',
            'main_block'
        )->setTemplate(
            'Jeff_Office::office/no4/hello.phtml'
        );

        $resultPage->getLayout()->setChild(
            'content',
            $customBlock->getNameInLayout(),
            'customblock_alias'
        );

        return $resultPage;  
    }
}

Mian.php Block file


#app/code/Jeff/Office/Block/Main.php

<?php
namespace Jeff\Office\Block;
class Main extends \Magento\Framework\View\Element\Template
{
    function _prepareLayout(){}

    public function helloPublic() {
        return 'Hello Public Block';
    }

    protected function helloProtected() {
        return 'Hello #2';
    }

    private function helloPrivate() {
        return 'Hello #3';
    }
}

jeff_office_index_index.xml layout file


#app/code/Jeff/Office/view/frontend/layout/jeff_office_index_index.xmal

<?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">
    <referenceBlock name="content">
        <block template="Jeff_Office::office/no4/template.phtml" class="Magento\Framework\View\Element\Template" name="jeff_office_block"/>
    </referenceBlock>
</page>

Three Template files for the Block usage

template.phtml file


#app/code/Jeff/Office/view/frontend/templates/office/no4/template.phtml

<h1>Template Title</h1>
<p>You should see this</p>
<p>You should see another this.</p>

example.phtml file


#app/code/Jeff/Office/view/frontend/templates/office/no4/example.phtml

<h2>Example Page</h2>
<p>Example Solution, Example, Example</p>
<p>Solution Example, Solution, Solution</p>

hello.phtml file


#app/code/Jeff/Office/view/frontend/templates/office/no4/hello.phtml

<h2>My Own Block Template</h2>
<p>Hello Tempatle</p>
<p><?php echo $block->helloPublic(); ?></p>


Install our new created module

Typing in following commands


php bin/magento module:enable Jeff_Office
php bin/magento setup:upgrade
php bin/magento cache:clean
php bin/magento cache:flush

Opening your browser, and type in http://yourdomain.com/jeff_office/index/index, you will see the result:


template screenshot


comments powered by Disqus