Skip to main content

Magento2 caching a blocks in a page

Blocks

A block is a modular unit of content that can be positioned most anywhere on the page. Content blocks are sometimes referred to as static blocks, or CMS blocks. They can be used to display fixed information such as text, images, and embedded video, as well as dynamic information that is provided by a widget or originates in a database or other source. Most elements on the home page are blocks that can be easily managed.

You can create custom blocks of content without writing any code, and assign them to appear in a specific place in the page layout. Blocks can be positioned using the Widget tool or by composing a layout update in XML and saving it on the server. For more information about using layout updates, see the Layout information in the Frontend Developer Guide.

 

Magento2 Block Cache

Caching plays an essential role in improving the page load time. In this article, I want to show you five blocks cache in Magento 2, or five approaches to caching, and when and how to use them. Interestingly, this article will cover both full page and block cache. Let’s explore each type of block cache together!

In case, cache_lifetime of the block is set to a number greater than 0, the block is cacheable

 

to cache any block, you need to override this function 

 

protected function getCacheLifetime()
{
    return 3600;
}
//below method to keep cache key unique for each block or page (try to set it as you like).
public function getCacheKeyInfo()
{
    $name =   $this->getProduct()->getId();
    $keyInfo     =  parent::getCacheKeyInfo();
    $keyInfo[]   =  $name; // adding the product id to the cache key so that each cache built remains unique as per the product page.
    return $keyInfo;
}

 

to know more about blocks please refer to this article