HUGO

Ordering of Data Template Dictionary (TOML tables) and Access to Keys

Short version:
(1) When I loop over the entries in a Data Template dictionary (a TOML table) - is the order based on the keys?
(2) Is there a way to loop over the keys?

Longer version:
I am using a Data Template (Data Templates | Hugo) where I load a TOML file.

In my TOML file I have a table:

    [tests.table]
    z="one"
    y="two"
    x="three"

In some simple tests, when I look over those tables in a template/shortcode, things are listed in the alphabetical order of the keys. So the above, when accessed by:

    {{ range $.Site.Data.workbooks.tests.table }}
    {{ . }}
    {{end}}

yields
three two one

(1)
This is actually very nice behavior! Can I count on it? (e.g., that the order of ranging over a dictionary loaded from TOML will be alphabetical based on key)

(2)
If I wanted to loop over the keys, not the values, how could I do it? For example, if I wanted to produce:
x y z
in the above example, how would I do that?

(2b) (bonus question)
If I wanted to loop over key value pairs (I guess if I had the keys, I could always just use index to look up the value), how would I do that. For example, in the example to produce
x three y two z one

Thanks!

Try: {{ range $index, $element := $.Site.Data.workbooks.tests.table }}

Within the scope of the above {{ $index }} wields the keys.

{{ $index }} {{ $element }}, should do it.

1 Like

Thank you! this is exactly what I needed! (for question 2 - although, this is a clue to the ordering question since I can look up how ranging over any dictionary works)

I would suggest that you don’t rely on this order. Dictionaries, i.e. maps, are by definition unordered. Go 1 Release Notes - The Go Programming Language

Thank you. That’s pretty clear that I cannot count on the order - even if it worked this afternoon.

But, it seems like sort can be applied to maps doing exactly what I want! So the easy answer (phew) seems to be:

{{ range sort $.Site.Data.workbooks.tests.table }}

to iterate over the dictionary in order.

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.