magento2 – Dynamically load CMS Block with Caching


We have a promo block added to the header via

app/design/frontend/(vendor)/(theme)/Magento_Theme/layout/default.xml

<!-- promo bar -->
<referenceContainer name="header.panel">
    <container name="header.panel.promo" htmlTag="div" htmlClass="header-top-promo" after="-"/>
</referenceContainer>

app/design/frontend/(vendor)/(theme)/Magento_Cms/layout/default.xml

<!-- header promo -->
<referenceContainer name="header.panel.promo">
    <block class="MagentoCmsBlockBlock" name="header.panel.promo.content">
        <arguments>
            <argument name="block_id" xsi:type="string">header_promo</argument>
        </arguments>
    </block>
</referenceContainer>

This is adding the CMS block “header_promo” to the site header. I’ve been tasked with removing this CMS block if the user has a certain cookie. I accomplished this with an observer (observing event layout_generate_blocks_after) to check for the cookie and removing the block if it exists. Essentially:

$layout = $observer->getData('layout');
$cookie = $this->_cookieManager->getCookie($cookieName);
if(!empty($cookie) {
    $layout->unsetElement("header.panel.promo.content");
}

The problem is this CMS block content gets cached, and will load despite the user having this cookie. If I clear the cache, the block will be removed as expected.

I’ve been looking into how to disable cache for this block. It looks like I don’t want to define this block in layout with cacheable="false" because that will disable cache for the entire page for all pages that include this block (all pages of the website since this is header content). It seems the proper way to do this is with Private Content, however I’m confused as how to implement this given my situation. I’ve defined my “section source class” with getSectionData() to return whether or not user has associated cookie, but I’m not using my own block class or template, just Magento core block/template to load a CMS block. Am I going about this the right away? What further steps should I take to achieve my goal?