1

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.

1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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