Magento 2

How to Create a Template Block in Magento 2

Block class and Layout XML
 
Magento 2 is now aware of our module, so let's create our block class. We'll do this by extending the \Magento\Framework\View\Element\Template class, and create a custom getName function:
 
Create a file Baz.php in new folder Foo/Bar/Block
<?php
namespace Foo\Bar\Block;
 
/**
* Baz block
*/
class Baz
    extends \Magento\Framework\View\Element\Template
{
    public function getTitle()
    {
        return "Foo Bar Baz";
    }
}
Note the changes from Magento 1; specifically setting a custom namespace and the new format for extending a block template, along with the new class.
 
Now that we have programmed our block, we want to display it on the home page. The naming of the file is important as this is the new way of using layout handles. The cms_index_index.xml name will make our block only appear on the home page (module_controller_action.xml).
 
Create our folder location:
 
mkdir -p app/code/Foo/Bar/view/frontend/layout
Then create a layout XML file at app/code/Foo/Bar/view/frontend/layout/cms_index_index.xml containing:
 
<?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="main">
            <block class="FooBarBlockBaz" template="default/baz.phtml"/>
        </referenceContainer>
    </body>
</page>
The referenceContainer element is referencing the layout container for our block. To read more about layout containers, please visit the official documentation on layouts. We also recommend reading thoroughly through the XML instructions for layouts to get a deeper understanding of the changes to the layout layer of Magento 2.
 
Template HTML and Caching
 
Next we'll create our folders for the template:
 
mkdir -p app/code/Foo/Bar/view/frontend/templates/default
Then the actual template HTML at app/code/Foo/Bar/view/frontend/templates/default/baz.phtml containing:
 
<?php
/**
 * Baz view template
 *
 * @var $block FooBarBlockBaz
 */
?>
<h1><?php echo $block->getTitle(); ?></h1>
If you need to flush the cache.
 
./bin/magento cache:flush --all # Flush all cache types
./bin/magento cache:flush layout  # Flush Layout XML

./bin/magento cache:flush full_page  # Flush Full Page Cache 

0 Bình luận

Trở về
  • Magento plug-ins
  • Magento plug-ins

    Magento2 gave very good concept called Plugin   we can do what ever after and before core function and also we have...

  • HOW TO CREATE MENU IN MAGENTO 2 ADMIN
  • HOW TO CREATE MENU IN MAGENTO 2 ADMIN

    magento-2-admin- menu My previous tutorial show you how to create a simple module in Magento 2, learn more here: http://www.venustheme.com/how-to-create-magento-2-module/....