I’ve managed to get some data to show up from a data file, but Hugo seems to be sorting my data alphabetically, which is not what I want to do.
here’s an example of some data (YAML):
b:
bar: 0
baz: 1
a:
bar: 2
baz: 3
And this is an example of the template I have
{{ range $.Site.Data.foo }}
{{ range . }}
{{ .bar }}
{{ end }}
{{ end }}
Instead of showing the data from b (i.e. where bar is 0) first (even though it’s first), it sorts alphabetically, and shows data from a instead (i.e. where bar is 2).
How can I modify this behaviour to get Hugo to render data in the order that it shows up in my data file? I tried to look up documentation on sorting, I did find some reference to sortByField, but I have no idea how or where to use it; or if it could even be used with data files at all (the docs seem to mention sortByField exists, but not much else).
In short: If what you define is a dictionary/map, the keys’ order will be undefined. Nothing to do about other than sorting it (there are a sort func in Hugo that may help you).
But I do suspect that you would be better off with reorg or your data file to make it an ordered list, pseudo YAML:
foo:
- name: a
bar: 0
baz: 1
- name: b
bar: 2
baz: 3
Note that I’m not sure the above is even valid YAML, but I hope the message is clear.
My memory is a little faded here, but I suspect you try to make sure you have a “root” in your YAML file so it is just not that list. But it is hard to tell without seeing the actual project.
Your suggestion of adding a root element to the YAML file seems like it could work, the loop works, however no data would actually show up (probably because I need to change something in my template to reflect the new data structure).
Since this was getting a bit too complex, I simply decided to work around it by naming the YAML key names to 0, 1, 2… not the most elegant solution, but I guess it works well.