Add Google Tag Manager container and dataLayer

Hi everyone,
just for developer and analyst 's hugers! Meanwhile I developed my blog (migration from wordpress), I had a tips about implementation of container (script) of Google Tag Manager.

So, here my guide how I implemented it.

file config.toml or similar
I added new params

[params]

Enable container by entering your Google Tag Manager container ID

google_tag_manager = “GTM-XXXXXX” // change XXX’s with your containerID

After in your theme > layouts > partials find your header.html

add before tag those lines:

{{ if $.Site.Params.google_tag_manager }}
  <!-- Google Tag Manager -->
  <!-- create dataLayer -->
  <script>
   <!-- OPTIONAL dataLayer -->
    var dataLayer = window.dataLayer = window.dataLayer || [];
    dataLayer.push({
      page:'{{ .Title }}',
      categories:'only examples about your dataLayer'
    });
  </script>
  <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.Params.google_tag_manager }}');</script>
  <!-- End Google Tag Manager -->
  {{ end }}

and after tag, first line:

  {{ if $.Site.Params.google_tag_manager }}
    <!-- Google Tag Manager (noscript) -->
    <noscript><iframe src="https://www.googletagmanager.com/ns.html?id={{ $.Site.Params.google_tag_manager }}"
    height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
    <!-- End Google Tag Manager (noscript) -->
  {{ end }}

It’s all and works fine your Google Tag Manager.

So, if you can add first dataLayer as my code, you can add new values.

You may want to wrap your google analytics code with

{{ if not .Site.IsServer }}
...
{{ end }}

So that your analytics results aren’t polluted when running hugo server locally.

Good point!
Yes, I had this rule above, instead old Google Analytics script, and I forgot to extend {{end}} at the final of Google Tag Manager script.

Thank you @zwbetz

Hi! In case others are reading this topic. I’m a digital analyst working on a Hugo blog. I’ve created a GTM integration for Hugo with Google Tag Manager. I wrote a blog to help you get started if you want to use it: How to add Google Tag Manager to Hugo.

The idea is to integrate the Hugo variables in the datalayer and also inject the container code into the website.

I hope it’s useful!