A Beginners Guide: Adding Templates to your first Module

Hi,

So building on top of the module that we created in the first post “Creating your First Module” in this post we are going to add a template and some JS to our module.

Step 1: Create your module

If you haven’t done so already, please navigate over to the “Creating your First Module” post and follow the instructions there first to get a basic module created.

Step 2: Create your Custom Block

Create a directory called “Block” in app/code/Johnadavies/Demo/ , in there create a block PHP file named something logical. We want a block that is for saying “hello World”, so we’re going to call it HelloWorld.php.

So you should have something like (YMMV):
app/code/Johnadavies/Demo/Block/HelloWorld.php

Go ahead and open this file up in your editor and in there we’re going to define our Block. Add the following class, swapping the namespace out for yours.

<?php
namespace Johnadavies\Demo\Block;
class HelloWorld extends \Magento\Framework\View\Element\Template
{
   
public function getHelloWorld(){ 
        return 'Hello world!'; 
    } 
}

You will also define methods here, but they have to return data not echo it out.

Step 3: Initial Structure

Navigate back to “app/code/Johnadavies/Demo” and create the following directories.

  • app/code/Johnadavies/Demo/view
  • app/code/Johnadavies/Demo/view/frontend
  • app/code/Johnadavies/Demo/view/frontend/layout
  • app/code/Johnadavies/Demo/view/frontend/templates

Step 4: Give your Block a Template

Create an appropriately named PHTML file in app/code/Johnadavies/Demo/view/frontend/templates which in our case is going to be called HelloWorld.phtml. So now I have:
app/code/Johnadavies/Demo/view/frontend/templates/HelloWorld.phtml

In that file add your code, such as:

<h1><?php echo $this->getHelloWorld(); ?></h1>

To call a method defined in our block, we simply as per Magento 1 refer to it as $this.

Step 5: Put our Block on the Page

We want our block to be located in the footer, so we need to tell Magento where to place it. so in app/code/Johnadavies/Demo/view/frontend/layout create a file called default.xml with the following content in:

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceBlock name="footer-container">
            <block class="Johnadavies\Demo\Block\HelloWorld" name="hello-world" template="HelloWorld.phtml"/>
        </referenceBlock>
    </body>
</page>

So long as you’ve installed your module previously you can now just run these commands and all being well it should show on the frontend:

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

Next in the series will be how to apply CSS and JS to your block

Leave a Reply

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