Shopping cart

How to get a block from template file phtml in Magento 2

In this topic, I really want to introduce you the way via php code to get a block from template phtml file in Magento 2. There are two examples I will give you here.

Example 1

If you need to call a template block helloworld.phtml of Mageplaza_HelloWorld, please use the below code:

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

Example 2

If you need to call template block in CMS static Block or CMS Page in Magento 2, please use the below code:


block class="Mageplaza\HelloWorld\Block\HelloWorld" name="your_block_name" template="Mageplaza_HelloWorld::helloworld.phtml"

Hope this is the helpful article to get block from template phtml file. In case that you have any queries about the article or any questions in general, use the comment section below!





Enjoyed the tutorial? Spread it to your friends!

magento-2-tutorial
get
block
from
template
file
phtml

Brian Tran
Brian Tran
Senior Magento Developer who is passionate about development and love technology

Comments for How to get a block from template file phtml in Magento 2

Please leave comments if you have any questions, feedbacks.

Module Development

We recommend:

You also may like these Magento 2 Extensions

One Step Checkout

$199
120 reviews

Layered Navigation

$99
61 reviews

Gift Card

$199
8 reviews

Reward Points

$99
8 reviews

Affiliate

$149
16 reviews

Shop By Brand

$99
19 reviews

People also searched for:

  • magento 2 get block from template file phtml
  • get block from template file phtml in magento 2
  • how to get block from template file
  • how to get block from template file phtml
  • how to get currency data in magento 2