Google Tag Manager (GTM) blade
Usage in Liquid:
...
{% include blades/gtm.liquid %}
</head>
<body>
{% include blades/gtm.liquid for_body=true %}
...
Living example: /anydigital/blades/blob/main/_includes/blades/html.liquid
Usage in Nunjucks:
...
{% include 'blades/gtm.njk' %}
</head>
<body>
{% set for_body = true %}{% include 'blades/gtm.njk' %}
...
Living example: /anydigital/blades/blob/main/_includes/blades/html.njk
Parameters:
site.gtm_id- Your Google Tag Manager container ID (e.g.,GTM-XXXXXXX)site.prod- Boolean flag to enable GTM only in productionfor_body- Boolean flag (default:false). Whenfalse, renders the script tag for the<head>. Whentrue, renders the noscript fallback for the<body>.
How it works
{% if site.prod and site.gtm_id %}
{% if not for_body %}
<!-- Google Tag Manager -->
<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;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','{{ site.gtm_id }}');</script>
<!-- End Google Tag Manager -->
{% else %}
<!-- Google Tag Manager (noscript) -->
<noscript><iframe src="https://www.googletagmanager.com/ns.html?id={{ site.gtm_id }}"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<!-- End Google Tag Manager (noscript) -->
{% endif %}
{% endif %}