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


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 -->
   <!-- OPTIONAL dataLayer -->
    var dataLayer = window.dataLayer = window.dataLayer || [];
      page:'{{ .Title }}',
      categories:'only examples about your dataLayer'
  new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
  })(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="{{ $.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.

1 Like

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!