How can I sort by date with Nunjucks?

I am trying to use jinja documentation to figure this out, but all my attempts are not working.

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

Here are some JSON test data:

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

How do I generate a sort code to sort by time?

I 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!

+4
source share
3 answers

Nunjucks only supports 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.imtqy.com/nunjucks/files/nunjucks.js"></script>
Run codeHide result
+3
source

Parse 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 this automatically

0
source

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

0
source

All Articles