I'm using Eleventy (11ty) with Nunjucks. I have some JSON data that I am trying to sort. The Jinja documentation says that you can sort by attribute using dot notation, but when I try sorting by address.city
, nothing happens:
{% for item in testData|sort(attribute="address.city") %}
{{ item.name }}
{% endfor %}
It does work if I sort without dot notation/by a top level field (name
):
{% for item in testData|sort(attribute="name") %}
{{ item.name }}
{% endfor %}
My test data (testData.json
):
[
{
"name": "AAA",
"address":
{
"city": "A?"
},
"salary": 2,
"married": true
},
{
"name": "III",
"address": {
"city": "D?"
},
"salary": 1,
"married": true
}
]
So, as seen in the comments to my question, sorting by dot notation isn't supported in Nunjucks currently.
What I did in the end, to get what I needed in my Nunjucks template in Eleventy, was to create a custom filter, inside of .eleventy.js
, along the lines of:
eleventyConfig.addFilter("sortByCity", arr => {
arr.sort((a, b) => (a.address.city) > (b.address.city) ? 1 : -1);
return arr;
});
Then, in my Nunjucks template:
{% for item in testData | sortByCity %}
{{ item.name }}
{% endfor %}
I know this answer is more 11ty-specific, but I think this could quite possibly work for other environments to extend Nunjucks. Hopefully this will be of help to someone else in the future. Nunjucks docs about Filters are here