I’m trying to add google tag manager to the head of my document.
Unfortunately, the way I’m doing it with an html tag render element, the ampersands (&) are being escaped.
function mymodule_page_attachments(array &$ page) { $ config = \Drupal::config('mymodule.config'); $ gtm_id = $ config->get('google_tag_manager_id'); $ gtm_auth = $ config->get('gtm_auth'); $ gtm_preview = $ config->get('gtm_preview'); /** @var \Drupal\mymodule\AnalyticsUtility $ utility */ $ utility = \Drupal::service('mymodule.utility'); if (!empty($ gtm_id) && !empty($ gtm_auth) && !empty($ gtm_preview) && $ utility->isAdminPage() === FALSE) { $ script = "(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start': new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0], j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src= 'https://www.googletagmanager.com/gtm.js?id='+i+dl+ '>m_auth={$ gtm_auth}>m_preview={$ gtm_preview}>m_cookies_win=x';f.parentNode.insertBefore(j,f); })(window,document,'script','dataLayer','{$ gtm_id}');\n"; $ page['#attached']['html_head'][] = [ ['#tag' => 'script', '#value' => $ script], 'google_tag_manager', ]; } }
This is resulting in ampersands in the code:
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start': new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0], j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src= 'https://www.googletagmanager.com/gtm.js?id='+i+dl+ '&gtm_auth=testrWktRcmjpViiQKW&gtm_preview=env-6&gtm_cookies_win=x';f.parentNode.insertBefore(j,f); })(window,document,'script','dataLayer','GTM-K53TEST');</script>
There are two modules with google tag manager and they both add the code using hook_page_attachments.
The recommendation for adding javascript is to use an external file, yet the google tag manager documentation recommends adding the script in the head.
Is there a way to do this with Drupal settings and a javascript file in my custom module?
Or is there a way to NOT convert the ampersands to HTML entities?