Hugo: Only show element when not localhost

Published: 2019-12-19 19:34:12 -0500 -0500

Reading time: 2 mins (255 words)

Tags: 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.

About the Ham

Hi I'm Hamilton and I wrote / built this! I like doing lots of things, but mostly I like to build (and then share those buildings). Some things I'm currently building: art, software, and prose. To stay up-to-date with my latest buildings, subscribe to my email list or follow one of my many other accounts. #buildit #shipit #justhamit

comments powered by Disqus