PHAM CONG NHAT
PHAM CONG NHAT

Reputation: 21

Magento2: How to make page non-cacheable in cms

I have added below code to load custom template file from a cms page.

{{block class="Test\PointHistory\Block\Index" template="Test_PointHistory::index.phtml"}}

I want to get the latest data every time I reload this cms page but it always returns data from full page cache.

Can anyone look into this and suggest me?

Upvotes: 0

Views: 1145

Answers (3)

PHAM CONG NHAT
PHAM CONG NHAT

Reputation: 21

I found a way to solve this issue. The steps I took to resolve this issue are as follows:

  1. Create a new page layout that inherits Magento's default page layout. Example

    app/design/frontend/<Vendor>/<theme>/Magento_Theme/page_layout/1column-disabled-fpc.xml`
    
    <?xml version="1.0"?>
    
    <layout xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_layout.xsd">
        <update handle="1column"/>
        <referenceContainer name="page.wrapper">
            <container name="one-column-disabled-cache" as="one-column-disabled-cache" htmlTag="div" htmlClass="disabled-fpc" />
        </referenceContainer>
    </layout>
    
    
  2. Create file

    app/design/frontend/<Vendor>/<theme>/Magento_Theme/layout/default.xml`
    
    <?xml version="1.0"?>
    
    <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
        <body>
            <referenceContainer name="one-column-disabled-cache">
                <block name="disabled-fpc" cacheable="false"/>
            </referenceContainer>
        </body>
    </page>
    
    
  3. Create file

    app/design/frontend/<Vendor>/<theme>/Magento_Theme/layouts.xml
    
    <?xml version="1.0" encoding="UTF-8"?>
    
    <page_layouts xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/PageLayout/etc/layouts.xsd">
        <layout id="1column-disabled-fpc">
            <label translate="true">1 column (Disabled FPC)</label>
        </layout>
    </page_layouts>
    
    
  4. Go to the Admin and change the layout of the CMS page to 1 column (Disabled FPC)

    enter image description here

Upvotes: 2

ronangr1
ronangr1

Reputation: 57

You have to override this getCacheLifetime() with:

public function getCacheLifetime()
{
    return null;
}

The other way (better) is to impletement the IdentityInterface

https://devdocs.magento.com/guides/v2.4/graphql/develop/identity-class.html

Upvotes: 0

L. Gerhardt
L. Gerhardt

Reputation: 127

You could override the getCacheLifetime() method in your block class to return null.

Upvotes: 0

Related Questions