Nunjucks 排序中的点符号不起作用
Dot notation in Nunjucks sorting isn't working
我在 Nunjucks 中使用 Eleventy (11ty)。我有一些要排序的 JSON 数据。您可以使用点表示法按属性排序的 Jinja documentation says,但是当我尝试按 address.city
排序时,没有任何反应:
{% for item in testData|sort(attribute="address.city") %}
{{ item.name }}
{% endfor %}
如果我在没有点 notation/by 的情况下对顶级字段 (name
):
进行排序, 是否有效
{% for item in testData|sort(attribute="name") %}
{{ item.name }}
{% endfor %}
我的测试数据(testData.json
):
[
{
"name": "AAA",
"address":
{
"city": "A?"
},
"salary": 2,
"married": true
},
{
"name": "III",
"address": {
"city": "D?"
},
"salary": 1,
"married": true
}
]
因此,正如我的问题的评论中所见,Nunjucks 目前不支持按点符号排序。
为了在 Eleventy 的 Nunjucks 模板中获得我需要的内容,我最后所做的是在 .eleventy.js
内创建一个 custom filter,按照以下行:
eleventyConfig.addFilter("sortByCity", arr => {
arr.sort((a, b) => (a.address.city) > (b.address.city) ? 1 : -1);
return arr;
});
然后,在我的 Nunjucks 模板中:
{% for item in testData | sortByCity %}
{{ item.name }}
{% endfor %}
我知道这个答案更针对 11ty,但我认为这很可能适用于其他环境来扩展 Nunjucks。希望这对将来的其他人有所帮助。 Nunjucks docs about Filters are here
我在 Nunjucks 中使用 Eleventy (11ty)。我有一些要排序的 JSON 数据。您可以使用点表示法按属性排序的 Jinja documentation says,但是当我尝试按 address.city
排序时,没有任何反应:
{% for item in testData|sort(attribute="address.city") %}
{{ item.name }}
{% endfor %}
如果我在没有点 notation/by 的情况下对顶级字段 (name
):
{% for item in testData|sort(attribute="name") %}
{{ item.name }}
{% endfor %}
我的测试数据(testData.json
):
[
{
"name": "AAA",
"address":
{
"city": "A?"
},
"salary": 2,
"married": true
},
{
"name": "III",
"address": {
"city": "D?"
},
"salary": 1,
"married": true
}
]
因此,正如我的问题的评论中所见,Nunjucks 目前不支持按点符号排序。
为了在 Eleventy 的 Nunjucks 模板中获得我需要的内容,我最后所做的是在 .eleventy.js
内创建一个 custom filter,按照以下行:
eleventyConfig.addFilter("sortByCity", arr => {
arr.sort((a, b) => (a.address.city) > (b.address.city) ? 1 : -1);
return arr;
});
然后,在我的 Nunjucks 模板中:
{% for item in testData | sortByCity %}
{{ item.name }}
{% endfor %}
我知道这个答案更针对 11ty,但我认为这很可能适用于其他环境来扩展 Nunjucks。希望这对将来的其他人有所帮助。 Nunjucks docs about Filters are here