Problem to use `where` in a database


#1

I have a database made of .yaml file looking like this

firstName: George
surname: Dupont
speaker: invited

I am trying to produce an numbered (and ordered) list of the invited speakers. I tried the following but it does not work. I do not get any output.

{{ range $index, $participant := sort (where .Site.Data.participants "speaker" "invited") "firstName" }}
  {{ $index }} -- {{ $participant.firstName }} {{ $participant.surname }} <br>
{{ end }}

Note that if get rid of where, by replacing (where .Site.Data.participants "speaker" "invited") with simply .Site.Data.participants it does produce something. But then I get a list of all speaker, whether or not they are invited.

Could someone be so kind and help me figure out what goes wrong with my where ?


#2

This is obviously untested, since I don’t know your full YAML data file, but try something like this:

{{ range $index, $participant := sort .Site.Data.participants "firstName" }}
  {{ if eq $participant.speaker "invited" }}
    {{ $index }} -- {{ $participant.firstName }} {{ $participant.surname }} <br>
  {{ end }}
{{ end }}

#3

Thank you for your quick answer. It does not work as I would like though. It does produce something like

13 -- Gerad Dupond
14 -- Nicolas Dupont
22 -- Marcelle Dupont
...

when I would like

1 -- Gerad Dupond
2 -- Nicolas Dupont
3 -- Marcelle Dupont
....

Here I understand what is the problem. There are basically 12 speakers which are not invited before the first invited speaker. With this solution the indexing is over all speakers and not the subset I am considering.


#4

The easiest solution is to remove the {{ $index }}, and use a html numbered list.

Otherwise, you can use Scratch to increment the numbering - https://gohugo.io/functions/scratch/


#5

Thanks for the suggestion. Actually what I ultimately want to do is different then just a numbered list. I presented the question this way in ordered to have a simple setting.


#6

Thanks, I will look into that.


#7

As @Jonathan_Griffin mentioned, use Scratch.

Or, do it this way:

{{ $count := 0 }}
<!-- some code here -->
{{ $count = add $count 1 }}

#8

Thanks @zwbetz the simple $count does the trick.