Home > Enterprise >  Drupal 9 : How to disable cache for a specific page
Drupal 9 : How to disable cache for a specific page

Time:12-23

How I can disable the cache of a specific page in Drupal 9, I found a solution, but it used to disable cache for all pages, the solution is: Add this code in settings.yml:

assert_options(ASSERT_ACTIVE, TRUE);
\Drupal\Component\Assertion\Handle::register();
$settings['container_yamls'][] = DRUPAL_ROOT . '/sites/development.services.yml';
$settings['cache']['bins']['render'] = 'cache.backend.null';
$settings['cache']['bins']['page'] = 'cache.backend.null';
$settings['cache']['bins']['dynamic_page_cache'] = 'cache.backend.null';

That's work, but I want just to disable cache for a specific page. Thanks.

CodePudding user response:

In the my_company.routing.yml config file for your page, you can add the following options.no_cache attribute :

my_company.customer_detail:
  path: '/customer/{customer_entity}/detail'
  defaults:
    _controller: '\Drupal\my_company\Controller\CustomerController::detailAction'
    _title: 'Fiche client'
  requirements:
    _permission: 'access content'
    type: ^\d 
  options:
    no_cache: 'TRUE'

CodePudding user response:

You can use hook_preprocess_HOOK in order to disable cache. Something like:

function test_module_preprocess_node__landing_page(&$variables) {
  $variables['#cache']['max-age'] = 0;
}

Where is test_module is your module name, node is your entity type and landing_page is your content type name. This hook should be placed in your module .module file.

Also, I recommend you to take a look at the Cache API article, where you can find how to control caching of your site and how to use cache contexts and tags

  • Related