Magento 2 disable cache block

Today we discuss about Magento 2 disable cache block .This tutorial include how to disable cache for block. There are two ways to do it. One is disable cache from layout xml for block or disable cache for block is programatically. So let start with our example.

layout cache disable

You can use cacheable=”false” attribute in your layout to disable cache for block but problem is that it will disable whole page cache.

<block class="QaisarSatti\HelloWorld\Block\HelloWorld" name="helloworld" cacheable="false" />

Another option for cache diable

<block class="QaisarSatti\HelloWorld\Block\HelloWorld" name="helloworld"  ttl="30" />

programmatically cache disable

Now the second option is disable cache for block programmatically.

<?php
/**
* Simple Hello World Module
*
* @category QaisarSatti
* @package QaisarSatti_HelloWorld
* @author Muhammad Qaisar Satti
* @Email qaisarssatti@gmail.com
*
*/

namespace QaisarSatti\HelloWorld\Block;
class HelloWorld extends \Magento\Framework\View\Element\Template
{
public function getCacheLifetime()
    {
        return null;
    }

}

Qaisar Satti

Hi, I'm Qaisar Satti! I've been a developer for over 20 years, and now I love sharing what I've learned through tutorials and guides. Whether you're working with Magento, PrestaShop, or WooCommerce, my goal is to make your development journey a bit easier and more fun. When I'm not coding or writing, you can find me exploring new tech trends and hanging out with the amazing developer community. Thanks for stopping by, and happy coding!

Leave a Reply