Magento 2 : Get customer_logged_in and customer_logged_out layout handles

Posted on March 31, 2016
Written by

I was working with a frontend developer who was complaining that Magento 2.0 no longer had the customer_logged_in and customer_logged_out layout handles that were extremely useful in Magento 1.

So I did some googling around and came across this stack overflow question where it became clear that other developers were also upset that this layout handle no longer existed. So I thought i’d be a nice chap and write a module to add them in.

Stack Overflow :

So this is how you do it. I called my module CustomHandles because I intend to reuse it to add any other custom layout handles that i require.

Start of with your usual registration.php, composer.json and module.xml files




Now the simple setup side of things is done, we need to register an observer that is triggered before our layout is loaded. This enables us to check if the customer is logged in or logged out and add the appropriate layout handle. There are two elements involved in this. Declaring the observer in our frontend/events.xml and the actual observer itself.



As you can see the observer itself is very simple, we add the customer session to our constructor and then add handles to the layout. If you want to test this you can add another observer for layout_generate_blocks_after and do observer->getEvent()->getLayout()->getUpdate()->getHandles(); to see your new handle added in the list of layout handles.

As an example of how to use the new handles i’ve created two xml files, one for logged in an done for logged out that will load a different phtml file into the of your Magento 2 installation dependent on the customers state.



Be sure to create your two template files : logged-in.phtml and logged-out.phtml

You may have also noticed that i’ve used a custom block class. You don’t have to do this, you can use Magento2’s standard block class : Magento\Framework\View\Element\Template but I thought since I don’t know what other layout handles I may want to add or what I may want in my template files I thought i’d create a block class that can be used later.



You can download the full module on git here :