Magento 2 – Add Layout Handle Based on Dynamic Value

layoutmagento-2.1magento2

I need to add a specific layout handle for all the pages when a certain value is present in the session.
To make it more clear, if $session->getMyValue() returns true I need to load a specific layout handle called my_specific_layout_handle on every page I visit.
In the code above $session is an instance of any subclass of Magento\Framework\Session\SessionManager (not really relevant).
Is there any event I can use or any method I can pluginize?

Note: I'm not concerned with full page cache for now. Let's say it does not exist.

Best Answer

For Adding Layout Handles You Can Use Event Also:

In Your events.xml

<event name="layout_load_before">
   <observer name="load_custom_handler" instance="[Vendor]\[Module]\Observer\LayoutLoadBefore" />
</event>

In Your LayoutLoadBefore.php

<?php

namespace [Vendor]\[Module]\Observer;

use [Vendor]\[Module]\Model\Session; //this is a custom session that extends `\Magento\Framework\Session\SessionManager`
use Magento\Framework\View\Result\Layout;

class LayoutLoadBefore implements \Magento\Framework\Event\ObserverInterface
{
    const MY_SPECIFIC_LAYOUT_HANDLE = 'my_specific_layout_handle';
    /**
     * @var Session
     */
    private $session;

    /**
     * LayoutPlugin constructor.
     * @param Session $session
     */

    public function __construct(
        Session $session
    )
    {
        $this->session = $session;        
    }

    /**
     * @param \Magento\Framework\Event\Observer $observer
     * @return $this
     */
    public function execute(\Magento\Framework\Event\Observer $observer)
    {
       if ($this->session->getMySpecificSessionValue()) { // YourCondition
           $layout = $observer->getLayout();
           $layout->getUpdate()->addHandle(self::MY_SPECIFIC_LAYOUT_HANDLE);
       }

       return $this;
    }
}