We have multiple environments such as Dev, Stage, QA, and Production. Rather than having one GTM snippet that is loaded on every page request in all the environments, we wanted to separate the GTM snippets so that the GTM snippet for Dev is only loaded for Dev, the GTM snippet for Stage is only loaded for Stage, and the production GTM script is only loaded on production.

Currently we add the GTM snippet through the use of our custom theme's html.html.twig template file.

How would I be able to conditionally add different scripts in a Drupal way (e.g. custom module, custom JS)?

We initially thought to create custom modules that would a load mymodule.html.html.twig when enabled per environment. For example, the dev custom module would only be enabled on Dev, Stage custom module would only be enabled on. However that is not working.

2 Answers 2


In my opinion adding a GTM snippet should be handled by a module, and not theme dependent. The GoogleTagManager can be used to accomplish this.

In your settings.php file you can indicate which snippet to use: $config['google_tag.settings']['container_id'] = 'GTM-000000';

When you want these snippet variants stored in you version control system, in that case every environment should have some kind of indicator allowing to implement something like:

if ($_ENV('ENVIRONMENT') == 'dev') {
    $config['google_tag.settings']['container_id'] = 'GTM-000000';
} elseif ($_ENV('ENVIRONMENT') == 'stage') {
    $config['google_tag.settings']['container_id'] = 'GTM-AAAAAA';

Another option to indicate which snippet to use depending on the current environment (i.e., Dev, Stage, QA or Production), is to use the Configuration Split module. This module contains functionality to create conditional splits.


Since google_tag started using containers, the format has changed a bit for the GTM settings, so you should now use the following:

$config['google_tag.container.label_machine_name_here']['container_id'] = 'GTM-000000';

label_machine_name_here is the machine name from whatever you called the GTM container in the module settings.

You can use the above method to change the GTM environment settings per development environment too, while keeping your GTM container id the same. The settings for that are:

$config['google_tag.container.label_machine_name_here']['environment_id'] = 'env-x';
$config['google_tag.container.label_machine_name_here']['environment_token'] = 'xxxxxx';

The quick way to know what the $config key is, is to look at the exported config filenames (from drush cex) - the filename for GTM is google_tag.container.label_machine_name_here.yml.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.