How to Create A Non-cacheable Block in Magento 2
Vinh Jacker | 3 days ago
The Most Popular Extension Builder for Magento 2
With a big catalog of 224+ extensions for your online store
Non-cacheable blocks in Magento 2 play a crucial role in shaping the caching behavior of web pages. Since these blocks are not cached, they are re-rendered on each request, ensuring that the latest information is always displayed to the user. Consequently, they are particularly useful for elements like shopping cart summaries, customer-specific content, or any other data that needs to be updated frequently.
In this guide, we’ll explore 2 effective methods to create a non-cacheable block in Magento 2. They consist of using a custom block class and any existing block. This will ensure that your dynamic content stays up-to-date for your customers. Let’s get started!
How to Create A Non-cacheable Block in Magento 2
In Magento 2, you can create a non-cacheable block by extending the \Magento\Framework\View\Element\Template
class and setting the cacheable attribute to false.
Here’s a basic 2 methods to achieve this:
Method 1: Use Custom Block Class
1 . Create your custom block class, which will extend the \Magento\Framework\View\Element\Template
class.
For example, name the custom block class NonCacheableBlock
<?php
namespace Vendor\Module\Block;
class NonCacheableBlock extends \Magento\Framework\View\Element\Template
{
/**
* @return bool
*/
protected function _isScopePrivate()
{
return true;
}
/**
* @return $this
*/
protected function _prepareLayout()
{
$this->addData([
'cache_lifetime' => false,
'cache_tags' => [],
'cache_key' => $this->getCacheKey()
]);
return parent::_prepareLayout();
}
}
- Create a template file in
app/code/Vendor/Module/view/frontend/templates/noncacheableblock.phtml
```
This is a non-cacheable block
3. Create layout XML file located in ``app/code/Vendor/Module/view/frontend/layout/default.xml``
<?xml version=”1.0”?>
4. Clear the cache after adding the block. Then check the content of the page
### Method 2: Use Any Existing Block
You can apply ``cacheable=”false” `` attribute directly in your layout XML file to disable cache for the block.
Run the code below :
<?xml version=”1.0”?>
``` In conclusion Creating non-cacheable blocks in Magento 2 allows you to display dynamic content that requires real-time updates without being affected by the caching mechanism. By following the steps outlined in this guide, you can make sure that your e-commerce website delivers a personalized and seamless experience for your customers.