Test for empty array with range

My frontmatter is being generated by a go program using https://github.com/BurntSushi/toml and it is automatically putting empty arrays when there are no vegetables or fruits in other cases.

For example, in my frontmatter I have the following:

[food]
  fruits = ["pear", "banana", "pineapple"]
  vegetables = [""]

In my layout/fruit/single.html I have this bit of code

{{range $key, $val := .Params.food}}
{{if not (eq $val "")}}
<span>{{delimit $val " · "}}</span>
{{end}}
{{end}}

The problem is that the resulting HTML has two <span> elements even though the .Params.food.vegetables is an empty array.

If I change my frontmatter to this:

[food]
  fruits = ["pear", "banana", "pineapple"]
  vegetables = "" <---- CHANGED HERE

The resulting HTML only has one <span> as desired.

How can I test for the empty array and only generate one <span> element?

UPDATE: Even the length test doesn’t work because [""] in the frontmatter is considered greater than 0, e.g.

{{range $key, $val := .Params.food}}
{{if gt (len $val) 0}}
{{delimit $val " · "}}
{{end}}
{{end}}

Try something like this:

{{ range $type, $val := .Params.food }}
{{ if gt (len $val) 0 }}{{   if not (eq (index $val 0) "") }}
<span>{{ delimit $val " . " }}</span>
{{ end }}{{ end }}

Note that $type will be fruits and vegetables, and $val will be the arrays.

2 Likes

Thank you that worked great :relaxed:

Btw I combined the two ifs like this:

{{if and (gt (len $val) 0) (not (eq (index $val 0) ""))}}

1 Like