Have Different Portions Of Code For Production And Development
Avoid Loading Adsense and Analytics when developing
Overview
When developing your website, you probably want to exclude some portions of code like Google Analytics or Adsense when running under hugo local server but have them in your final site.
Here are some alternatives to do it.
Detecting Hugo’s built-in server
This is the easiest way to prevent code from executing when running the local server.
When you run hugo server command, Hugo sets the boolean
variable .Site.IsServer
to true
.
.Site.IsServer: a boolean to indicate if the site is being served with Hugo’s built-in server.
Run code only in production:
{{ if not .Site.IsServer }}
<!--ONLY PRODUCTION-->
{{ template "_internal/google_analytics_async.html" . }}
{{ end }}
Run code only in development:
{{ if .Site.IsServer }}
<!--ONLY DEVELOPMENT-->
{{ end }}
Or both:
{{ if .Site.IsServer }}
<!-- DEVELOPMENT -->
{{"<!-- Googla analytics placeholder -->" | safeHTML}}
{{ else }}
<!-- PRODUCTION -->
{{ template "_internal/google_analytics_async.html" . }}
{{ end }}
Using environment variables
You can also set environment variables and read their value in Hugo’s templates with the function getenv:
getenv: Takes a string containing the name of the variable as input. Returns an empty string if the variable is not set, otherwise returns the value of the variable.
When running the server, first export HUGO_ENV=production or run it directly: HUGO_ENV=production hugo
Having in your templates:
{{ if eq (getenv "HUGO_ENV") "production" | or (eq .Site.Params.env "production") }}
{{ template "_internal/google_analytics_async.html" . }}
{{ end }}
This way you can use the environment variable in your code or also set a parameter in configuration.
Only in development:
{{ if ne (getenv "HUGO_ENV") "production" }}
{{ partial "custom-stats.html" . }}
{{end}}
References
- https://gohugo.io/variables/site/
- Add .Site.IsServer to determine if the site was built in server mode #4478
- https://discourse.gohugo.io/t/distinguish-production-from-development/2855/8
- https://discourse.gohugo.io/t/how-to-exclude-google-analytics-when-running-under-hugo-local-server/6092/7
- Have Different Portions Of Code For Production And Development
- Deploying a Hugo website to AWS in 6 steps (CDN+HTTPS)August 12, 2018
- Customizing Bootstrap 4 with Hugo pipesAugust 7, 2018
- A first approach to Hugo for Jekyll developersAugust 4, 2018
- How I migrated this website articles from Jekyll to HugoAugust 4, 2018
- Hugo overview and basic conceptsOctober 10, 2017
Articles
Except as otherwise noted, the content of this page is licensed under CC BY-NC-ND 4.0 . Terms and Policy.
Powered by SimpleIT Hugo Theme
·