1

I want to show a popup phtml based on wether a cookie has been set or not in my block class.

The logic is roughly:

class Popup extends \Magento\Framework\View\Element\Template
{
    public function shouldShowPopup()
    {
        if ($this->cookie->get()) {
            return false;
        }
        return true;
    }
}

Then in the phtml:

if ($block->shouldShowPopup() ) {
    echo 'HTML Content here';
}

My issue is that shouldShowPopup() seems to be caching, so I'm getting inconsistent results.

Is there a way to mark this so as not to be cached? I have tried

<argument name="cache_lifetime" xsi:type="number">0</argument>

which doesn't have any effect and also:

<block class="Block\Class" name="blockname" cacheable="false" />

which removed the cache from the whole page.

If (like I have read elsewhere) this is not possible, should this logic be implemented somewhere more suitable outside of the block class?

  • Did you try using JS? – Sohel Rana Jan 30 at 16:15
  • No. That is a fall back option. – engbmaso Jan 30 at 16:18
0

The reason why it is being cached because by default the block will have a static cache key.

In your case I'd suggest to set the cache_key of your block to a session variable of the visitor that you can also extract via the cookies. This way the block will still be cached and reused - but correctly, as the any other visitor will have a different session variable and their own cached block.

Look into the \Magento\Framework\View\Element\AbstractBlock class, getCacheKey() method.

To add your own getCacheKey() logic simply just create this method in your block and control the caching logic of the block by controlling the return value (either random everytime or based per session id or something else.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.