最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can I sort by date with Nunjucks? - Stack Overflow

programmeradmin1浏览0评论

I'm trying to use the jinja documentation to figure it out but all my attempts are failing.

Here is some test JSON data:

items: [{
        name: 'item 1',
        time: '2015-02-12T00:38:18.055Z'
    },{
        name: 'item 2',
        time: '2014-01-12T00:40:18.881Z'
    }]

How should I form the sort code so that I can sort by time?

I'ved tried:

{% for item in items|sort%}

and

{% for item in items|sort(attribute='time')%}

and

{% for item in items|sort('time')%}

and

{% for item in items|sort(time)%}

and

{% for item in items|sort(item.time)%}

But nothing works. Thank you!

I'm trying to use the jinja documentation to figure it out but all my attempts are failing.

http://jinja.pocoo.org/docs/dev/templates/#sort

Here is some test JSON data:

items: [{
        name: 'item 1',
        time: '2015-02-12T00:38:18.055Z'
    },{
        name: 'item 2',
        time: '2014-01-12T00:40:18.881Z'
    }]

How should I form the sort code so that I can sort by time?

I'ved tried:

{% for item in items|sort%}

and

{% for item in items|sort(attribute='time')%}

and

{% for item in items|sort('time')%}

and

{% for item in items|sort(time)%}

and

{% for item in items|sort(item.time)%}

But nothing works. Thank you!

Share Improve this question asked May 26, 2015 at 1:34 sjmartinsjmartin 3,9624 gold badges21 silver badges32 bronze badges 0
Add a comment  | 

3 Answers 3

Reset to default 14

Nunjucks only seems to support positional arguments:

{% for item in items|sort(false, true, 'time') %}
{{item.name}}<br>
{% endfor %}

var res = nunjucks.renderString("{% for item in items|sort(false, true, 'time') %}{{item.name}}<br>{% endfor %}", { items: [{
        name: 'item 1',
        time: '2015-02-12T00:38:18.055Z'
    },{
        name: 'item 2',
        time: '2014-01-12T00:40:18.881Z'
    }] });

document.body.innerHTML = res;
<script src="https://mozilla.github.io/nunjucks/files/nunjucks.js"></script>

Now nunjucks already supports arguments, so {% for item in items|sort(attribute='time')%} works fine

Parse the time as Epoch time and pass it as another attribute so you can sort it.

items: [{
    name: 'item 1',
    time: '2015-02-12T00:38:18.055Z',
    epoch: 1232323532
}]

Or use a custom filter that does it automatically

发布评论

评论列表(0)

  1. 暂无评论