Is it possible to get the block name of the current template?

For example I added a block to catalog_product_view.xml:

<block class="Magento\Contact\Block\ContactForm" name="firstname"
        <argument name="required" xsi:type="boolean">0</argument>

How can I get the name of the block (firstname) inside the template .phtml file?

I tried:


$name = $block->getName();   // Output -> empty     Expected: firstname

4 Answers 4


I figured it out:

All Methods are defined here: vendor\magento\framework\View\Element\AbstractBlock.php

It works like this:


$name = $block->getNameInLayout();       // Output -> firstname

This code class="Magento\Contact\Block\ContactForm" means that in your template you have access to all methods of the class vendor/magento/module-contact/Block/ContactForm.php or Magento\Framework\View\Element\Template

In that class you have no getName method.

What do you need? the name entered in the form? in this case you need to use javascript. The name of the current user (if he is logged in)? You need to extend the class or add a viewModel


You need to create a model that will represent your table and will hold your class also, then you need to have resource model and collections, then in your layout file using collections and the method defined in your block of $block->getName() will execute will give you the correct result.


Layout file:

<block class="Magento\NegotiableQuote\Block\Quote\Info" name="quote.status"

So you can use $blockname = $block->getNameInLayout() for fetching the "name" assigned to the block in layout file, e.g comment.status.

Or you can use var_dump(get_class($block)); to fetch the class of the block.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.