Disable Google Analytics While Running Hugo Test Server
So while I was writing my previous post I realized that Google Analytics was being called from the localhost server. I also had lots of grief with Disqus back when I migrated to Hexo; It filled my account with posts related to localhost. I wonder why Disqus built it this way.
I hard-coded the Disqus URL in my theme (Both Hexo and Hugo) but then realized I can’t do the same for Google Analytics. I needed a way to disable it altogether. The fix turned out to be quite simple.
1{{ if ne (printf "%v" $.Site.BaseURL) "http://localhost:1313/" }}
2{{ template "_internal/google_analytics_async.html" . }}
3{{ end }}
It works for both Google Analytics and Disqus. It should apply to other cases as well.
Another approach also mentioned on the page is to use two configuration files, one for testing and one for production, and make the testing file the default.
1// config-release.toml
2BaseURL = "http://mydomain.com/"
3PublishDir = "/var/www/mysite"
4[params]
5 isRelease = true
6
7// config.toml
8BaseURL = http://localhost:1313/
9
10// layout
11{{ if .Site.Params.isRelease }}
12 some release code, like Google Analytics
13{{ else }}
14 some dev code, like logging
15{{ end }}
And use hugo switches to choose when to write the production files
1// to release
2hugo --config ./config-release.toml
3
4// to dev
5hugo server
The first approach is enough for simple sites, but you might need to use the second approach if you need something more complex.
Update: 1/3/2018 As I am learning more about the ever evolving Hugo, I found I can just use the below in a partial
1{{- if in (string .Site.BaseURL) "localhost" -}}
2 some dev code, like logging
3{{- else -}}
4 some release code, like Google Analytics
5{{- end -}}
About Me
Dev gone Ops gone DevOps. Any views expressed on this blog are mine alone and do not necessarily reflect the views of my employer.
Recent Posts