Skip to main content
2 of 4
deleted 1 character in body

Magento 2 - nearly empty registry when trying to get current category in top menu

I want to get the current shown category in \Magento\Theme\Block\Html\Topmenu.

When using the anti-pattern Objectmanager approach in phtml via:

$objectManager =  \Magento\Framework\App\ObjectManager::getInstance();
$registry = $objectManager->get('\Magento\Framework\Registry');

Or using some dependency-injection via:

class Topmenu extends \Magento\Theme\Block\Html\Topmenu {
    protected $_registry;

    public function __construct(
        Template\Context $context,
        NodeFactory $nodeFactory,
        TreeFactory $treeFactory,
        array $data = [],
        \Magento\Framework\Registry $registry
    ) {
        $this->_registry = $registry;
        parent::__construct($context, $nodeFactory, $treeFactory, $data);
      }

    public function _prepareLayout(){
        return parent::_prepareLayout();
    }

    public function getRegistry() {
        return $this->_registry;
    }

    public function getCurrentCategory() {
       return $this->_registry->registry('current_category');
    }
}

I alway get a nearly empty Registry-Model like:

object(Magento\Framework\Registry)#128 (1) { ["_registry":"Magento\Framework\Registry":private]=> array(1) { ["use_page_cache_plugin"]=> bool(true) } }

What am I doing wrong that when i call "getCurrentCategory()" it is NULL?

Further thoughts: Is there a place where i have to do a kind of _initCategories()? Is the registry restricted?