Nunjucks在循环内,将属性转换为int并按int排序?

问题描述 投票:0回答:1

我有一个对象:

[
  {
   "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 }}') %}
int jinja2 nunjucks
1个回答
1
投票

您可以seenunjucks使用字符串比较器对元素进行排序(默认为js行为)。因此,您应先将block -property转换为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);
© www.soinside.com 2019 - 2024. All rights reserved.