mozilla / nunjucks

A powerful templating engine with inheritance, asynchronous control, and more (jinja2 inspired)
https://mozilla.github.io/nunjucks/
BSD 2-Clause "Simplified" License
8.48k stars 634 forks source link

groupby changes order of an array if values are integers #1434

Open Brixy opened 1 year ago

Brixy commented 1 year ago

Hi all,

if you take this example from the Nunjucks website …

{% set items = [
        { name: 'james', type: 'green' },
        { name: 'john', type: 'blue' },
        { name: 'jim', type: 'blue' },
        { name: 'jessie', type: 'green' }
    ]
%}

{% for type, items in items | groupby("type") %}
    <b>{{ type }}</b> :
    {% for item in items %}
        {{ item.name }}
    {% endfor %}<br>
{% endfor %}

… the order of the array is respected: green comes before blue:

Output

green : james jessie
blue : john jim

But if you use integers (or even quoted integers) …

{% set items = [
        { name: 'james', type: 2 },
        { name: 'john', type: 1 },
        { name: 'jim', type: 1 },
        { name: 'jessie', type: 2 }
    ]
%}

… the output is sorted numerically:

Output

1 : john jim
2 : james jessie

Expected output

2 : james jessie
1 : john jim

Is this Nunjucks issue or the expected behavior? Is there a way to avoid sorting by integers?


A practical workaround: Values for year have to be strings here, for example 2023- (with trailing hyphen).

{% for year, posts in posts | groupby("year") %}
    <h2>{{ year | replace("-", "") }}</h2>
    {% for post in posts %}
        <article>{{ post.title }}</article>
    {% endfor %}
{% endfor %}

Thank you.

NextThread commented 10 months ago

hey, can I work on this issue