Disable cache for a specific page | Drupal 8

Disable cache for a specific page

Submitted by editor on Sun, 09/17/2017 - 12:57
Question
  • How to disable cache for a custom page ?
  • How to disable cache for a specific content type ?

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'

 

Disable cache for a specific content type

Example:

function yourmodule_node_view(array &$build, NodeInterface $node, $display, $view_mode) {
  if ($node->getType() == 'yourtype' && $view_mode == 'full') {
    $build['#cache']['max-age'] = 0;
  }
}

 

Disable cache from a controller.

Note : This will work in no cache on page level (not working for anonymous users for example).

Set cache max age on rederer array.

$output = [];
$output['#cache']['max-age'] = 0;

 

Add new comment