循环中的 Nunjucks,将属性转换为 int 并按 int 排序?
Nunjucks within loop, convert attribute to int and sort by int?
我有一个对象:
[
{
"block": "1",
...
"block": "2",
...
"block": "11"
并且我想按整数而不是字符串(对 1、11、2 进行排序)对块进行排序:
<!-- sorts as string -->
{% for standard in standards | sort(false, true, 'standard.block') %}
我尝试将 standard.block
转换为 int
但没有效果
{% for standard in standards | sort(false, true, '{{ standard.block | int }}') %}
尽你所能 see:nunjucks
使用字符串比较器对元素进行排序(默认 js 行为)。因此,您应该在排序之前将 block
-属性 转换为 Number 或使用自定义过滤器,例如sortBy
const nunjucks = require('nunjucks');
const env = nunjucks.configure();
env.addFilter('sortBy', function (arr, prop) {
const isNum = val => val == +val;
const sorter = (a, b) => isNum(a[prop]) && isNum(b[prop]) ? +a[prop] - b[prop] : a[prop] < b[prop];
arr.sort(sorter);
return arr;
});
const html = env.renderString(
`{% for item in items | sortBy('block') %}
{{item.block}} {{ item.color}}
{% endfor %}`,
{
items: [
{ block: "1", color: 'Blue' },
{ block: "7", color: 'Green' },
{ block: "3", color: 'Yellow' }
]
}
);
console.log(html);
我有一个对象:
[
{
"block": "1",
...
"block": "2",
...
"block": "11"
并且我想按整数而不是字符串(对 1、11、2 进行排序)对块进行排序:
<!-- sorts as string -->
{% for standard in standards | sort(false, true, 'standard.block') %}
我尝试将 standard.block
转换为 int
但没有效果
{% for standard in standards | sort(false, true, '{{ standard.block | int }}') %}
尽你所能 see:nunjucks
使用字符串比较器对元素进行排序(默认 js 行为)。因此,您应该在排序之前将 block
-属性 转换为 Number 或使用自定义过滤器,例如sortBy
const nunjucks = require('nunjucks');
const env = nunjucks.configure();
env.addFilter('sortBy', function (arr, prop) {
const isNum = val => val == +val;
const sorter = (a, b) => isNum(a[prop]) && isNum(b[prop]) ? +a[prop] - b[prop] : a[prop] < b[prop];
arr.sort(sorter);
return arr;
});
const html = env.renderString(
`{% for item in items | sortBy('block') %}
{{item.block}} {{ item.color}}
{% endfor %}`,
{
items: [
{ block: "1", color: 'Blue' },
{ block: "7", color: 'Green' },
{ block: "3", color: 'Yellow' }
]
}
);
console.log(html);