Hugo: Only show element when not localhost
Date: 2019-12-19 | hugo | development | localhost |
problem
I have some elements on my site that I only want to appear when I'm not running my Hugo site via localhost via the hugo serve
command. How can I have some elements conditionally show up only when in production?
solution
1. set environment variables
The first way you can do this is to set environment variables. From the docs, this can be set like:
env HUGO_VARIABLE="Some Title" hugo
You can then read this environment variable into your hugo site via:
{{ getenv "HUGO_VARIABLE" }}
This is highly flexible as you can use this to control pretty much anything based on environment but does require a little work and seems a little unwieldy if you decide to use more than a few variables.
2. check the .Site.IsServer
variable
The .Site.Server
variable tells you if the default hugo server (the way hugo serves via hugo serve
) is being used to serve the site or not. By leveraging it, you can conditionally show content based on whether or not you're running via localhost.
Here's a quick example:
{{ if not .Site.IsServer }}
<div>
I only show in production
</div>
{{ end }}
This method is super simple but will only work if you run on something other than the default hugo serve
server (which is recommended btw). I use it personally to only log analytics to Google when I'm not running my site locally because I really only have two modes (and thus don't need the extra flexibility of environment variables) and I run on NGINX.
Want more like this?
The best / easiest way to support my work is by subscribing for future updates and sharing with your network.