Magento 2 Set Block template

Today we talk about how in Magento 2 Set Block template. This tutorial included set block template in layout file, block file . Following this example you can get store date and time in block, helper, controller or model too. So let start with our example.

In layout File

    <block class="QaisarSatti\HelloWorld\Block\HelloWorld" name="HelloWorld" template="QaisarSatti_HelloWorld::HelloWorld.phtml"></block>

In Block File

Used the _construct() method to set template.

protected function _construct()
    {
        parent::_construct();
        $this->setTemplate('QaisarSatti_HelloWorld::HelloWorld.phtml');
    }

Another way to set template in block in set the $_template variable to your template.

protected $_template = 'QaisarSatti_HelloWorld::HelloWorld.phtml';

Qaisar Satti

Hi, I'm Qaisar Satti! I've been a developer for over 20 years, and now I love sharing what I've learned through tutorials and guides. Whether you're working with Magento, PrestaShop, or WooCommerce, my goal is to make your development journey a bit easier and more fun. When I'm not coding or writing, you can find me exploring new tech trends and hanging out with the amazing developer community. Thanks for stopping by, and happy coding!

Leave a Reply