Drupal - How can I prevent a particular page being cached?
For Drupal 7:
Drupal has the function drupal_page_is_cacheable() which can be used to set a page to uncacheable.
Here is the documentation: https://api.drupal.org/api/drupal/includes!bootstrap.inc/function/drupal_page_is_cacheable/7
For Drupal 8:
// Deny any page caching on the current request.
\Drupal::service('page_cache_kill_switch')->trigger();
Then the code is:
public function myPage() {
\Drupal::service('page_cache_kill_switch')->trigger();
return [
'#markup' => time(),
];
}
As usual, clean your cache once done.
Disable cache for a specific page
Disable cache for a custom page from route declaration. If you want to disable cache for a custom controller (Custom module), You have
no_cache
option (YOUR_MODULE.routing.yml). Example : File : mymodule.routing.yml
mymodule.myroute:
path: '/mymodule/mypage'
defaults:
_controller: '\Drupal\mymodule\Controller\Pages::mypage'
_title: 'No cache page'
requirements:
_access: 'TRUE'
options:
no_cache: 'TRUE'
Added 'no_cache' route option to mark a route's responses as uncacheable
In Drupal 8, you can mention cache as max-age till you want your page ouput to be cached. For removing cache of a particular page(Controller page), write 'max-age' => 0,
.
public function myPage() {
return [
'#markup' => time(),
'#cache' => ['max-age' => 0,], //Set cache for 0 seconds.
];
}