Drupal - How do I disable Twig and block cache for a specific module?
You can control the cache in the render array with the #cache element.
To disable the cache add:
$build['#cache']['max-age'] = 0;
In this case the block will not be cached for logged in users or anonymous users with a session.
If you want to disable the cache for anonymous users without a session:
Disable it either by uninstalling the page_cache module completely or by triggering the kill switch, see How can I prevent a particular page being cached? for example.
The caching of the twig code is not connected to this, the twig code is only cached once, the first time it is used after you cleared the cache.
(edit acc. to comments of Berdir)
To stop caching a specific block use the following function:
/**
* Implements hook_preprocess_HOOK() for block.html.twig.
*/
function template-name_preprocess_block(&$vars) {
if($vars['derivative_plugin_id'] == 'add-block-id-name') {
//-- This stops the block being cache in drupal 8
$vars['#cache']['max-age'] = 0;
}
}
Disable cache for a specific page/content type/controller
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