Hugo isset in templates

As in almost any programming language, you can check if a parameter is set using isset in Hugo templates.

From the documentation we get a clear description, what isset makes:

isset:
Returns true if the parameter is set. Takes either a slice, array or channel and an index or a map and a key as input.

Lets go through a few examples that explains the functionality:

Assume we have the following simple data-structure from the front matters in toml:

[database]
  server = "192.168.1.1"
  ports = [ 8001, 8001, 8002 ]
  connection_max = 5000
  enabled = true

isset accepts two parameters - where to look, and the parameter that should be available.

Example: Check if database is available

{{ isset .Params "database" }} // true
{{ isset .Params "pony" }} // false

So we can to use this boolean in an if-statement like this:

{{ if isset .Params "database" }}
  Yeah! A database is available.
{{ else }}
  Sadly no database is available :-(
{{ end }}

Example: Check if a given index is available

In database.ports there is a list. We can now check if there is a value under a given index:

{{ isset .Params.database.ports 0 }} // true (8001)
{{ isset .Params.database.ports 1 }} // true (8001)
{{ isset .Params.database.ports 2 }} // true (8002)
{{ isset .Params.database.ports 3 }} // false

The above statements looks pretty clear, but please be aware, that minus index-values always return true, even the key does not exist:

{{ isset .Params.database.ports -1 }} // true

Example: Iteration through lists

To make the isset method a bit more useful. Lets iterate through a list with range and check if we can find a value or not.

First of all we create a list of keys where are available in an ideally:

{{ $keys := (slice "host" "server" "location" "ports" "connection_max" "enabled") }}

Next we loop through the $keys with range and check if the properties are defined in the database and get the value with index

<ul>
{{ range $keys }}
    <li>{{ . }} : {{ if isset $.Params.database . }}{{ (index $.Params.database . ) }}{{ else }}Not available.{{ end }}</li>
{{ end }}
</ul>

This returns a list like this:

  • host : Not available.
  • server : 192.168.1.1
  • location : Not available.
  • ports : [8001 8001 8002]
  • connection_max : 5000
  • enabled : true