且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Mustache.js中数组元素的索引

更新时间:2023-11-17 08:54:10

另一种解决方案,无需使用Mustache.js



您可以使用< ol>< / ol> 代替胡子愚弄< ul>< / ul> ,它将为每个项目添加前缀 index + 1

An alternative solution, without fooling around with Mustache.js

Instead of fooling around with mustache you might as well use a <ol></ol> instead of <ul></ul>, that will prefix each item with index+1.

如果您愿意,可以使用css将起始编号更改为0,它将完全按照您的需要进行渲染。您甚至可以在数字后更改,例如 - ,问题就解决了。

If you'd like you can use css to change the starting number to 0, and it will render exactly as you want. You can even change the dot after the number, to something such as " - ", and problem is solved.

<ol>
  <li>Mercury</li>
  <li>Venus</li>
  <li>Earth</li>
  <li>Mars</li>
</ol>

以上内容将呈现为:

1. Mercury
2. Venus
3. Earth
4. Mars






Mustache.js的方法



如果你想在胡子中做这个,那么正确的方法是将您的字符串数组转换为对象数组,其中包含索引和字符串值。


the Mustache.js way to do it

The proper method if you'd like to do it in mustache is to convert your array of strings to an array of objects, where index and string value is present.

// I wrote this from the back of my head, it's untested and not guaranteed
// to work without modifications, though the theory behind it is valid.


var array     = ["123","***","abc"];
var obj_array = [];

for (idx in array)
   obj_array.push ({'index': idx, 'str': array[idx]});

var view     = {items: obj_array};
var template = "<ul>{{#items}}<li>{{index}} - {{str}}</li>{{/items}}</ul>";
var html     = Mustache.to_html(template,view);