Hugo isset in Templates
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.
{{ 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 }}
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
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