Add Customer Layout Handles in Magento 2

Magento 1 provided the useful ability to add layout updates depending on whether the customer was logged in or out of their account. For some reason, Magento 2 does not contain these layout handles by default. Below will describe the steps needed to add customer layout handles in Magento 2.

To start with, add a custom module containing a registration.php and module.xml file.

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    '[Vendor]_[Module]',
    __DIR__
);
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="[Vendor]_[Module]" setup_version="1.0.0" />
</config>

Enable the module and upgrade the database by running the following commands from your Magento root directory.

/path/to/php bin/magento module:enable [Vendor]_[Module]
/path/to/php bin/magento setup:upgrade

The customer layout handles will be added via an event observer. The event in particular that needs to be ‘observed’ is the layout_load_before event.

Create an events.xml within the module’s etc/frontend directory and define the observer.

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="layout_load_before">
        <observer name="add_customer_handles" instance="[Vendor]\[Module]\Observer\AddCustomerHandlesObserver" />
    </event>
</config>

Create the observer, which will be responsible for adding in the customer_logged_in and customer_logged_out layout handles. You can use getUpdate()->addHandle() from the layout object passed in the event.

In addition, inject the Magento\Customer\Model\Session class that can be used to check whether the customer is logged in or not.

<?php
namespace [Vendor]\[Module]\Observer;

use Magento\Customer\Model\Session;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;

class AddCustomerHandlesObserver implements ObserverInterface
{
    /**
     * @var Session
     */
    private $customerSession;

    /**
     * AddCustomerHandlesObserver constructor.
     *
     * @param Session $customerSession
     */
    public function __construct(
        Session $customerSession
    )
    {
        $this->customerSession = $customerSession;
    }

    /**
     * @param Observer $observer
     * @throws \Magento\Framework\Exception\LocalizedException
     */
    public function execute(Observer $observer)
    {
        $layout = $observer->getEvent()->getLayout();

        if ($this->customerSession->isLoggedIn()) {
            $layout->getUpdate()->addHandle('customer_logged_in');
        } else {
            $layout->getUpdate()->addHandle('customer_logged_out');
        }
    }
}

Now you’ll have the ability to add layout updates within a customer_logged_in.xml and a customer_logged_out.xml file.

Add these layout files within the module’s view/frontend/layout directory. As an example, the layout files shown below add a template that renders content depending on whether the customer is logged in or not.

<?xml version="1.0"?>
<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="customerhandles.loggedin"
                   after="-" template="[Vendor]_[Module]::customer_logged_in.phtml" />
        </referenceContainer>
    </body>
</page>
<div class="loggedin-container">
    <p><?php echo __('Content showing for logged in customers'); ?></p>
</div>
<?xml version="1.0"?>
<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="customerhandles.loggedout"
                   after="-" template="[Vendor]_[Module]::customer_logged_out.phtml" />
        </referenceContainer>
    </body>
</page>
<div class="loggedout-container">
    <p><?php echo __('Content showing for logged out customers'); ?></p>
</div>

Refresh the cache, and you should notice that the content that appears is dependent on whether the customer is logged out or in.

Add Customer Layout Handles in Magento 2

Add Customer Layout Handles in Magento 2

Note: This article is based on Magento Open Source version 2.2.