Magento 2 – Disabling Cache for Specific Block

blockscachemagento2

In my module, I am adding small snippet to every page on site with layout file, that I have attached below. The thing is, I would like to disable caching for my module. How do I do that without disabling FPC for whole page? Using cacheable="false" will make whole page non-cached. So this option won't work for me.

I have already tried following:

  1. controlling cache through the constructor, my block derives from \Magento\Framework\View\Element\Template and setting up cache like this : $this->addData(array('cache_lifetime' => null)); didn't work.

  2. adding parameters to my block in layout file:

    <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
            <body>
                <referenceContainer name="content">
                    <block class="Something\Something\Block\SnippetBlock" name="snippetblock" template="snippetblock.phtml"> 
                     <arguments>
                                        <argument name="cache_lifetime" xsi:type="null">null</argument>
                              </arguments>
                </block>
                </referenceContainer>
            </body>
    

  3. overwriting getCacheLifetime() method to return null.
    And this is my layout file that I am using now:

    <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="content">
            <block class="Something\Something\Block\SnippetBlock" name="snippetblock" template="snippetblock.phtml" />
        </referenceContainer>
    </body>
    

I will gladly listen to any suggestion.

Best Answer

In Magento2, You have to render the content via JS (Ajax).
Check how the mini-cart & login/logout section has been implemented.

Note: There is no concept like hole-punching like in Magento 1.