janl/mustache.js

prevent automatic array sorting in template

arnold-yolabs opened this issue · 2 comments

My array looks like this:

items = [
  'foo',
  'bar',
  'baz'
];

And I want to use a mustache template to produce something like this (list items rendered in the order they appear in the array):

<ul>
  <li>foo</li>
  <li>bar</li>
  <li>baz</li>
</ul>

However, when I use the following code:

fs.readFile('path/to/template.html', async function(err, data) {
  out = Mustache.render(data.toString(), {
      items: items
  });
  resolve.send(out);
});

and the following html template:

<ul>
  {{#items}}
  <li>{{.}}</li>
  {{/items}}
</ul>

my final output looks like this, with the array items sorted:

<ul>
  <li>bar</li>
  <li>baz</li>
  <li>foo</li>
</ul>

How can I prevent mustache from sorting array values on render?

Hi!

I can't think of anything inside mustache.js that sorts that array for you. I put what you shared above into a keep-it-simple-stupid reproduction, and the ordering of items is kept as is after being rendered:

https://jsbin.com/lixubumica/edit?js,output

If you could make a reproduction for us that does some kind of unexpected sorting, that would be really helpful.

Thank you for helping me narrow down the issue I was experiencing. After a lot of digging and researching, the data sorting issue was occurring in a process hidden to me in the middle of the pipeline, before I was even retrieving the list items for display (even though my data was sorted correctly at the start of the pipeline).