Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I sort by date with Nunjucks?

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!

like image 688
sjmartin Avatar asked May 26 '15 01:05

sjmartin


2 Answers

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>
like image 118
Ja͢ck Avatar answered Oct 18 '22 08:10

Ja͢ck


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

like image 25
aavf Avatar answered Oct 18 '22 07:10

aavf