[SOLVED] Google Analytics template only working on homepage

A pull request has been raised on my Hugo Theme, Massively, which makes use of Hugo’s internal Google Analytics template rather than using a custom implementation:

However, this is only working on the homepage. The snippet is included in the root index.html as:

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

The source of the following files shows Google Analytics only appearing on the homepage:

Why is this?

Thanks!

I have implemented Google Analytics this way and it works on every page:

In config.toml:

googleAnalytics = "UA-123-45"

[params]
    env    = "PUBLIC"

In template:

{{ if and (eq .Site.Params.env "PUBLIC") (ne .Site.GoogleAnalytics "") }}
    {{ template "_internal/google_analytics_async.html" . }}
{{ end }}

Hope this helps.

Added explanation:
The if-condition reads like: If the Environment is “PUBLIC” and the GoogleAnalytics Parameter in config.toml is not empty include the internal template.

This is a double check which takes care that the internal template is not taken if there’s no Google Analytics ID even if the environment is PUBLIC.

Hope this makes sense…

The reason it’s only showing on the home page is, it’s added only to the index.html template, but not to the single.html.

Ah of course! Thanks

Forgot to mention that I have the above snippet in the baseof.html so I have no need to put the snippet in single.html or other templates because they’re all using baseof.html.

1 Like

Thanks, that makes a lot of sense

Glad it helped. Please see my additional remarks above under ‘Added explanation:’