4

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?

14

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!

  • 1
    Thanks. Works nicely. I found that I can also inject an instance of \Magento\Framework\View\Context and call $context->getFullActionName(), but I guess your method is cleaner. \Magento\Framework\View\Context has a lot of other objects injected and I may not need them. – Marius Jan 11 '15 at 13:19
1

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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