Magento – Magento 2: Cacheable false for specific block not working

block-cachecachefull-page-cachemagento2

I am trying to detect user’s country based on their IP address and ability to change country as well. However with the use of Full Page Cache, country name is not getting display properly. Sometimes it displays random results.

I have tried to add cacheable=false to block XML file. But adding this would slow down entire page. Since this block is added to all pages, entire site getting slow by adding cacheable=false.

Also tried _isScopeprivate = true to my block PHP __construct() function. But this is also not working.

Is there any way to exclude specific block from FPC without hurting site speed?

I have rewrite currency.phtml template for customize my goal,

<referenceContainer name="header.panel">
            <block class="Vendor\Module\Block\Currency" name="currency" template="Vendor_Module::currency.phtml" cacheable="false"/>
</referenceContainer>

when i am keep cacheable=false in above block its working but page load time take so much time.
So I want to remove cacheable="false" from above block.

Any suggestion would be appreciated.
Thanks.

Best Answer

cacheable=false on a block makes whole page not cacheable. This is how it is designed, so no problem here.

As for your goal - you want to render user-specific content as part of cached page. Such content should not be rendered on server. It should be retrieved from server using customer data JS api (see mini shopping cart), and rendered using JS.

Alternatively you can redirect user to proper country page based and not care about it on magento side.

Related Topic