Magento 2 – How to Get Current Page Layout Handle

event-observerlayoutmagento2-dev-beta

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?

Best Answer

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!