Magento – Magento 2 EE : Need to remove one single block from cache

block-cachecachefull-page-cachemagento2-enterprise

I just need to remove single block phtml from FPC cache. How can I do that without using cacheable = "false". Because cacheable = "false" has an effect on the whole page.

I am using a .phtml file in the static block and that static block call into header.

Best Answer

You can create a preference or a plugin on the block class to override the block cache functions: getCacheLifetime(), hasCacheLifetime(), get/hasCacheTags(), has/getCacheKeyInfo(), getData().

If getCacheLifetime returns null than it will disable current block's cache.

Take a look at the block class to see which cache methods it uses and search in parent block classes (Abstract, Template, ..) to see which function you need to override in your plugin/preference class.

cacheable = "false" has only one meaning. It will disable full page cache type on that page type / action.

If there is something wrong with the parameters that form cache key info, than you can vary block cache by overriding getCacheKeyInfo function.

If there is customer specific data inside that block than you can't use either block cache or have it in full page cache. The only viable solution is to use AJAX. Magento 2 has private content: http://devdocs.magento.com/guides/v2.3/extension-dev-guide/cache/page-caching/private-content.html

Other solution is to use AJAX requests to fill parts of pages like in product page reviews and other. https://github.com/magento/magento2/blob/2.2-develop/app/code/Magento/Review/view/frontend/web/js/process-reviews.js

The last and the least is the XML layout declaration ttl="3600". When Magento 2 is configured to work with Varnish, it will create am ESI policy for the output of the block. Something similar does when it uses builtin page cache instead of Varnish. Magento uses this type of cache hole punching in one place: in top menu. I personally don't recommend using "ttl" cache hole punching because it adds an extra request to the server. If you use it too many times on a page than it may decrease performance.

Related Topic