Magento 2: How to call any template block from phtml file?

In Magento 1.x, you could call/print any module’s template block in any other template (phtml) file with the following code:


echo $this->getLayout()
          ->createBlock('newmodule/newblock')
          ->setTemplate('newmodule/newblock.phtml')
          ->toHtml();

In Magento 2.x, it’s slightly different.

Below is the code to call/print a custom template block in another template file in Magento 2.

Suppose, you want to call a template block (helloworld.phtml) of module Chapagain_HelloWorld, then you should write the following code:


echo $this->getLayout()
          ->createBlock('Chapagain\HelloWorld\Block\HelloWorld')
          ->setTemplate('Chapagain_HelloWorld::helloworld.phtml')
          ->toHtml();

If you would like to call template block in CMS static Block or CMS Page in Magento 2, then you can simply write the following code:

Let’s take the same example as above (calling helloworld.phtml of module Chapagain_HelloWorld).


{{block class="Chapagain\HelloWorld\Block\HelloWorld" name="your_block_name" template="Chapagain_HelloWorld::helloworld.phtml"}}

Passing variable or parameter to the block

You can also pass variables or parameters while calling the .phtml template from CMS Page or Static Block.


{{block class="Chapagain\HelloWorld\Block\HelloWorld" name="your_block_name" title="My Title" count="10" template="Chapagain_HelloWorld::helloworld.phtml"}}

You can see above that we have passed two extra variables/parameters (title and count) to the block code.

Now, to access these variables from your template (.phtml) or block class (.php) file, you have to write the following.


$title = $this->getData('title');
$count = $this->getData('count');

For the example of this article, this code can be written in both template (Chapagain\HelloWorld\view\frontend\templates\helloworld.phtml) and block class (Chapagain\HelloWorld\Block\HelloWorld.php) file.

Hope this helps. Thanks.