janl / mustache.js

Minimal templating with {{mustaches}} in JavaScript
https://mustache.github.io
MIT License
16.37k stars 2.4k forks source link

prevent automatic array sorting in template #794

Closed arnold-yolabs closed 2 years ago

arnold-yolabs commented 2 years ago

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?

phillipj commented 2 years ago

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.

arnold-yolabs commented 2 years ago

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).