Skip to content

Instantly share code, notes, and snippets.

@ccharlton
Created July 10, 2024 17:21
Show Gist options
  • Save ccharlton/7f09a61ebbed7eff927de19128035191 to your computer and use it in GitHub Desktop.
Save ccharlton/7f09a61ebbed7eff927de19128035191 to your computer and use it in GitHub Desktop.
CacheTag Inject module for Drupal
name: 'CacheTag Inject'
type: module
description: 'Allows developers to edit an array of Node IDs or URI paths to assign specific CacheTags.'
core_version_requirement: ^10
package: Custom
dependencies:
- drupal:node
<?php
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Routing\RouteMatchInterface;
/**
* Implements hook_help().
*/
function cachetag_inject_help($route_name, RouteMatchInterface $route_match) {
switch ($route_name) {
case 'help.page.cachetag_inject':
return '<p>' . t('Allows developers to edit an array of Node IDs or URI paths to assign specific CacheTags.') . '</p>';
}
}
/**
* Implements hook_page_attachments_alter().
*/
function cachetag_inject_page_attachments_alter(array &$attachments) {
// Array of Node IDs or URI paths to assign specific CacheTags.
$items_to_cache = [
// Example Node IDs.
'node/1',
'node/2',
// Example URI paths.
'some/custom/path',
];
// Define the cache tags you want to inject.
$cache_tags = [
'custom_tag_1',
'custom_tag_2',
];
// Get the current path.
$current_path = \Drupal::service('path.current')->getPath();
$current_path_alias = \Drupal::service('path_alias.manager')->getAliasByPath($current_path);
// Check if the current path or its alias is in the list.
if (in_array($current_path, $items_to_cache) || in_array($current_path_alias, $items_to_cache)) {
$cache_metadata = new CacheableMetadata();
$cache_metadata->setCacheTags($cache_tags);
$cache_metadata->applyTo($attachments['#cache']);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment