How to Add a Custom Google Analytics Template in Hugo


How can we customize our Google Analytics file in Hugo?

Our Hugo template might include a line that looks like one of these:

{{ template "_internal/google_analytics.html" . }}
{{ template "_internal/google_analytics_async.html" . }}

We want to replace this with our own partial template that injects the Google Analytics script tag.

1. Add googleAnalytics property

First, we want to ensure we have a googleAnalytics property set in our configuration.

Let’s open our config.yaml or config.toml or config.json, and add this property.

...
googleAnalytics: "UA-000000000-0"
...

This value is our Tracking ID, which is available when we register our website with Google Analytics.

2. Create a new google_analytics.html

Next, we’ll want to create a new partial to inject our custom Google Analytics script tag.

We can save this file in /layouts/partials.

{{- with .Site.GoogleAnalytics -}}
  <script>
    window.dataLayer = window.dataLayer || [];
    function gtag(){dataLayer.push(arguments);}
    gtag('js', new Date());
    gtag('config', '{{ . }}');
  </script>
  <script async src="https://www.googletagmanager.com/gtag/js?id={{ . }}"></script>
{{- end -}}

3. Replace old templates

Finally, we’ll want to find the file responsible for using the internal Google Analytics template. This will be the file that generates the <head> tag with one of the lines below. In many Hugo projects, this will be baseof.html.

{{ template "_internal/google_analytics.html" . }}
{{ template "_internal/google_analytics_async.html" . }}

Let’s replace the line with the partial.

{{ partial "google_analytics.html" . }}

If we don’t want to load Google Analytics when running locally, we can wrap the partial injection in a conditional.

{{- if not .Site.IsServer }}
  {{ partial "google_analytics.html" . }}
{{- end }}