Search code examples
javascriptmustache

Mustache js order by


I know that Mustache is a "logic less" template scripting but probably what I'm looking for exist...

Imagine to have a model like this:

var users = [{
    {name: "Lorem", isOk: false},
    {name: "Ipsum", isOk: true},
    {name: "Dolor", isOk: false},
    {name: "Sit", isOk: false},
    {name: "Amet", isOk: true}
}];

When I create the template for users:

{{#users}}
    <p>{{name}}</p>
{{/users}}

It render everything in the model order.

Is there a chance to load first the isOk: true and after them the others?

I tried with:

{{#users}}
    {{#isOk}}
    <p>{{name}}</p>
    {{/isOk}}
    {{^isOk}}
    <p>{{name}}</p>
    {{/isOk}}
{{/users}}

But nothing change...


Solution

  • The {{#users}} wraps the whole list so the contents is repeated for each element. You'd have to have to iterate twice over the list in order to split it like this.

    {{#users}}
        {{#isOk}}
        <p>{{name}}</p>
        {{/isOk}}
    {{/users}}
    {{#users}}
        {{^isOk}}
        <p>{{name}}</p>
        {{/isOk}}
    {{/users}}
    

    Of course you could separate the list before you run over it twice:

    // in js, divide in good & bad, join afterwards
    var goodUsers = [], 
        badUsers = [],
        sortedUsers = [];
    users.forEach(function(user) {
      if (user.isOk) {
        goodUsers.push(user);
      } else {
        badUsers.push(user);
      }
    });
    sortedUsers = goodUsers.concat(badUsers);
    

    This way you'd only have to use your code once, but operate on the sorted list:

    {{#sortedUsers}}
        <p>{{name}}</p>
    {{/sortedUsers}}