Skip to content

Instantly share code, notes, and snippets.

@Lego2012
Last active September 18, 2017 13:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Lego2012/8994f2e05306b3248442382ca52ce4c8 to your computer and use it in GitHub Desktop.
Save Lego2012/8994f2e05306b3248442382ca52ce4c8 to your computer and use it in GitHub Desktop.
Hugo isset in Templates #hugo

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment