Для кэширования блоков в Drupal 9 на основе пути вы можете использовать следующие методы:
Метод 1: использование перехватчика Block Cache Alter
/
* Implements hook_block_cache_alter().
*/
function your_module_block_cache_alter(&$data, $block) {
// Get the current path.
$current_path = \Drupal::service('path.current')->getPath();
// Add the current path to the block cache key.
$data['keys'][] = 'path:' . $current_path;
}
Метод 2. Использование службы динамического кэша страниц
use Drupal\Core\Cache\CacheableMetadata;
use Symfony\Component\HttpFoundation\RequestStack;
/
* Implements hook_preprocess_HOOK() for block templates.
*/
function your_module_preprocess_block(&$variables) {
// Get the current path.
$current_path = \Drupal::service('path.current')->getPath();
// Add the current path to the cache metadata.
$cache_metadata = new CacheableMetadata();
$cache_metadata->addCacheContexts(['url.path']);
$cache_metadata->addCacheKeys(['path:' . $current_path]);
// Apply the cache metadata to the block.
$variables['#cache'] = $cache_metadata->mergeCacheableMetadata($variables['#cache']);
}
Метод 3. Непосредственное использование Cache API
use Drupal\Core\Cache\Cache;
/
* Implements hook_preprocess_HOOK() for block templates.
*/
function your_module_preprocess_block(&$variables) {
// Get the current path.
$current_path = \Drupal::service('path.current')->getPath();
// Generate a cache ID for the block using the path.
$cache_id = 'block:' . $variables['elements']['#id'] . ':path:' . $current_path;
// Add the cache ID to the block cache tags.
$variables['#cache']['tags'][] = $cache_id;
// Add the cache ID to the block cache contexts.
$variables['#cache']['contexts'][] = 'url.path';
// Set the maximum age for the block.
$variables['#cache']['max-age'] = Cache::PERMANENT;
}