Magento – How to disable the cache for the block in Magento 2

cachemagento2

protected function _construct()
    {
        $this->addData(
            [
                'cache_lifetime' => false,
                'cache_tags' => array('MY_BLOCK'),
            ]
        );
    }

    public function getCacheKeyInfo()
    {
        return [];
    }

does not work. Why? How to disable the cache for block?

Best Answer

Blocks can be set as non-cacheable by setting the cacheable attribute false in layout XML files. For example

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

Pages containing such blocks are not cached.

Also check How do disable caching of custom block

Edit: A single cacheable="false" will disable Full Page Caching for the whole page, making the pages sourcing from that layout file extremely slow! Check https://inviqa.com/blog/how-full-page-cache-works-magento-2

Related Topic