Ronalds Vilciņš

How to add Google Tag Manager code to your Hugo website

In config.toml add new params and change XXX’s with your containerID.

   gtm = "GTM-XXXXXX"

Find your themes header.html partial and add Google Tag Manager code anywhere between the <head> tags.

{{ if $.Site.Params.gtm }}
  <!-- Google Tag Manager -->
  <!-- create dataLayer -->
   <!-- OPTIONAL dataLayer -->
    var dataLayer = window.dataLayer = window.dataLayer || [];
      page:'{{ .Title }}',
      categories:'Your dataLayer'
  new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
  })(window,document,'script','dataLayer','{{ $.Site.Params.gtm }}');</script>
  <!-- End Google Tag Manager -->
  {{ end }}

Right below the <body> element, include the following code snippet.

{{ if $.Site.Params.gtm }}
    <!-- Google Tag Manager (noscript) -->
    <noscript><iframe src="{{ $.Site.Params.gtm }}"
    height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
    <!-- End Google Tag Manager (noscript) -->
 {{ end }}

You may want to add preconnect and prefetch features for better performance.

<link href="" rel="preconnect" crossorigin>
<link rel="dns-prefetch" href="">

To exclude Google Tag Manager code from the localhost website, copy your code into an if statement like this:

{{ if not (in (.Site.BaseURL | string) "localhost") }}
{{ end }}

That’s it!