Working with the data layer
Google Tag Manager pushes its data layer value to the data layer before the container starts, so the container's tags and triggers can use each value as a "Data Layer Variable". GoatCounter sets its data as window.goatcounter settings before count.js loads.
| Service | Plugin ID | Data layer variable |
|---|---|---|
| GoatCounter | goatcounter |
window.goatcounter: the data is GoatCounter's settings, such as path and title, starting with the options turned on in the service. |
| Google Tag Manager | google_tag_manager |
dataLayer, or the service's "Data Layer variable" setting |
Google Tag Manager's data starts as the service's "Data layer value JSON" setting. To add values from code, such as the type and ID of the page's entity, implement hook_analytics_SERVICE_ID_data_alter(), where SERVICE_ID is the analytics service's ID, or hook_analytics_PLUGIN_ID_data_alter() for every service that uses a plugin. Both are documented with examples in analytics.api.php.
use Drupal\analytics\Plugin\ServicePluginInterface;
use Drupal\Core\Cache\RefinableCacheableDependencyInterface;
use Drupal\Core\Hook\Attribute\Hook;
use Drupal\helper\CurrentEntity;
class MyModuleHooks {
public function __construct(
protected readonly CurrentEntity $currentEntity,
) {}
/**
* Implements hook_analytics_SERVICE_ID_data_alter() for the 'gtm' service.
*/
#[Hook('analytics_gtm_data_alter')]
public function analyticsGtmDataAlter(array &$data, ServicePluginInterface $service, RefinableCacheableDependencyInterface $cacheability): void {
// The page's main entity, such as the node on a node's page or its tabs.
$cacheability->addCacheContexts(['route']);
if ($entity = $this->currentEntity->fromRouteMatch()) {
$cacheability->addCacheableDependency($entity);
$data['entityType'] = $entity->getEntityTypeId();
$data['entityBundle'] = $entity->bundle();
$data['entityId'] = $entity->id();
}
}
}
Values are encoded as JSON, so use strings, numbers, booleans, NULL and arrays.
The data is part of the cached page. Add the cache tags and contexts of anything the values depend on to $cacheability, as the example does for the route and the entity, so the page is updated when the entity changes and varies by what the values vary by, such as the user.roles context for the user's roles.
Choosing which pages are tracked
To change which pages a service tracks, implement hook_analytics_service_access(), also documented in analytics.api.php. It is core's access hook for the analytics_service entity type, and the track operation decides whether a service outputs on a request. Return forbidden to stop tracking, and allowed to track where the service's plugin is neutral. Add the cache contexts of anything the access result depends on.
Data layer in your own plugin
A plugin with a data layer uses Drupal\analytics\Plugin\ServiceDataTrait, implements defaultData(), and outputs what getData() returns, which invokes the alter hooks. It passes getData() a CacheableMetadata object and applies it to the output array itself: cache metadata inside #attached['html_head'] items doesn't reach the page.
use Drupal\analytics\Plugin\ServiceDataTrait;
use Drupal\Core\Cache\CacheableMetadata;
class ExampleTagManager extends ServicePluginBase {
use ServiceDataTrait;
public function defaultData() {
return json_decode($this->configuration['data_layer'] ?: '[]', TRUE) ?? [];
}
public function getOutput() {
$cacheability = new CacheableMetadata();
$data_js = '';
if ($data = $this->getData($cacheability)) {
$data_js = 'window.exampleLayer.push(' . Json::encode($data) . ');';
}
// ...
$cacheability->applyTo($output);
return $output;
}
}