Add Google Analytics to Hugo blog

We will do two things: add a partial and use it in templates, and set up Google Analytics to include in this partial

Create a partial for GA code

I keep all partials inside the theme, for cleaner development. The partials can be nested, to simplify each individual component, so we will create a folder footer inside the theme partials directory and add ga.html partial inside it.
The path will look like this:

Site Root
    └── themes
        └── clearcase
            └── layouts
                └── partials
                    └── footer
                        └── ga.html

This path is the second place Hugo will look for partials, so to include it you only need to use this shortcode in your template:

{{ partial "footer/ga.html" . }}

The final part is the ga.html itself. It uses the new global site tag code.

<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-129657799-1"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', '{{ .Site.GoogleAnalytics }}');
</script>

Configure site config.toml with GA code

Add this to your config.toml file:

googleAnalytics = "UA-12345678-1"

You are all set. When you load the page for the first time you should see the realtime data in Analytics console right away.

October 17, 2019   (v.5abcbe5)