Question

In Magento 1 I could get the current page layout handle like this

$handle = Mage::app()->getFrontController()->getAction()->getFullActionName();

This would return for example for a product page catalog_product_view or cms_index_index for homepage.

How can I do the same thing in Magento 2?

I need to get a page handle from within an observer. What should I inject in the constructor in order to be able to access it?

Was it helpful?

Solution

I believe you will need to inject

\Magento\Framework\App\Request\Http into the constructor and then do:

$handle = $this->_request->getFullActionName();

Tested this in Magento\Catalog\Model\Observer - addCatalogToTopmenuItems() as below and it did the trick:

public function __construct(
    ...
    \Magento\Framework\App\Request\Http $request
) {
    ...
    $this->_request = $request;
}

public function addCatalogToTopmenuItems(\Magento\Framework\Event\Observer $observer)
{
    $handle = $this->_request->getFullActionName();
    ....
}

This is one of the first times i'm playing with Magento2 may be completely the wrong way to do this!

OTHER TIPS

You have to just add below line for Template view file and Block file to get current action name of page.

This is nice working with any template file and block file,

echo $this->getRequest()->getFullActionName();

Output will gives current action name of page.

For product page, catalog_product_view , for category page catalog_category_view

You can have access in any $block by calling $block->getLayout()->getUpdate()->getHandles().

If you prefer, you can create a new module and inject this block in the end of content. For example:

#app/code/Vendor/Module/view/frontend/template/handle.phtml
<?php
use Vendor\Module\Block\Handles;

/** @var Handles $block */
?>
<p>All Handles</p>
<pre><?php var_dump($block->getLayout()->getUpdate()->getHandles());?></pre>

<p>Full Action Name</p>
<pre><?php echo $block->getRequest()->getFullActionName();?></pre>
<!-- app/code/Vendor/Module/view/frontend/layout/default.xml -->
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="content">
                <block class="Magento\Framework\View\Element\Template" name="handler_debugger"  template="Vendor_Module::handle.phtml"/>
        </referenceContainer>
    </body>
</page>

This would also print the layout handles at the end of any frontend page.

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top