In this post, we will see how to create blocks in Magento 2.

  1. Make sure you have created your module, if not, click here to create one.
  2. Make sure you have following directory structure:
    <Mymodule>
         <Test>
              <Block>
              <etc>
                  module.xml
              <view>
                  <frontend>
                       <layout>
                       <templates>
              registration.php
  3. Now, we will create our block class named Customdate.php under the Block folder. Add following code to it:
    <?php
    namespace Mymodule\Test\Block;
    
    use \Magento\Framework\View\Element\Template;
    
    class Customdate extends Template
    {
        public function getDate($format)
        {
            if($format=="mdy")
                return date("m/d/Y");
            else if($format=="dmy")
                return date("d/m/Y");
            else if($format=="ymd")
                return date("Y-m-d");
            else
                return date();
        }
    }
  4. Next, we will create our xml file for layout. Create the file cms_index_index.xml file under the layout folder. The name cms_index_index is important here as it represents the path to our home page.
    The path must match:

    frontName action_path_name controller_name
    

    If you have a look under following path: /vendor/magento/module-cms, you will find Index.php at /Controller/Index folder.
    Now, frontName is defined as cms in etc/frontend/routes.xml
    Hence, the path to match becomes cms_index_index  (frontName_ActionPath_ControllerName)

    Add following code to the above created file:

    <?xml version="1.0"?>
    <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../../lib/internal/Magento/Framework/View/Layout/etc/page_configuration.xsd">
        <body>
            <referenceContainer name="content">
                <block class="Mymodule\Test\Block\Customdate" template="custom_date.phtml"/>
            </referenceContainer>
        </body>
    </page>
  5. Next we create the template file that is associated with this block. Create file named custom_date.phtml under view/frontend/templates folder and add following code to it:
    <h1><?php echo $block->getDate("ymd"); ?></h1>

    Our block is now ready. Just clear your cache and visit your home page.