Javascript Mustache.js 中数组元素的索引

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8567413/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 06:32:07  来源:igfitidea点击:

Index of an array element in Mustache.js

javascriptiteratormustache

提问by Dane

This is what I'd like to do in Mustache.js but not seeing how with the documentation.

这是我想在 Mustache.js 中做的,但没有看到文档如何。

var view = {items:['Mercury','Venus','Earth','Mars']};
var template = "<ul> {{#items}}<li>{{i}} - {{.}}</li>{{/items}} </ul>";
var html = Mustache.to_html(template,view);

Desired output:

期望的输出:

<ul>
  <li>0 - Mercury</li>
  <li>1 - Venus</li>
  <li>2 - Earth</li>
  <li>3 - Mars</li>
</ul>

回答by Alexar

Looking for a fast clean solution?

正在寻找快速清洁的解决方案?

Simply add an indexfunction

只需添加一个index功能

var data = {
    items: [{
            name: Aliasghar
            , grade: 19
        }, {
            name: Afagh
            , grade: 20
    }]
    , index: function() {
        return ++window['INDEX']||(window['INDEX']=0);
    }
}

and your template could be like this:

你的模板可能是这样的:

{{#items}}
    {{index}} -- {{name}} is {{grade}}
{{/items}}


How it works

这个怎么运作

We add a index: function(){}to data and we use it as a normal function in template. This function adds a key to the windowobject which is available globally; then increases it one by one.

我们将 a 添加index: function(){}到数据中,并将其用作模板中的普通函数。该函数window为全局可用的对象添加一个键;然后一一增加。

To use with multiple lists

与多个列表一起使用

Please note that if you are using multiple templates one after another you need to either reset window['INDEX']or change it's key to something else like window['YEKI_DIGE']. Another way of doing this is by adding a resetIndexfunction. Here is the way:

请注意,如果您一个接一个地使用多个模板,您需要重置window['INDEX']或将其更改为其他类似window['YEKI_DIGE']. 另一种方法是添加一个resetIndex函数。这是方法:

var data = {
    items: [{
            name: Aliasghar
            , grade: 19
        }, {
            name: Afagh
            , grade: 20
    }]
    , index: function() {
        return ++window['INDEX']||(window['INDEX']=0);
    }
    , resetIndex: function() {
        window['INDEX']=null;
        return;
    }
}

and your template could be like this:

你的模板可能是这样的:

{{#items}}
    {{index}} -- {{name}} is {{grade}}
{{/items}}
{{resetIndex}}

Inspired by this answer: https://stackoverflow.com/a/10208239/257479from daveon In Mustache, How to get the index of the current Section

通过这个答案的启发:https://stackoverflow.com/a/10208239/257479戴夫在胡子,如何获得当前部分的索引

回答by Filip Roséen - refp

An alternative solution, without fooling around with Mustache.js

一种替代解决方案,无需使用 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.

与其胡闹胡须,还不如使用一个<ol></ol>代替<ul></ul>,它将为每个项目添加前缀index+1

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 dotafter the number, to something such as " - ", and problem is solved.

如果您愿意,可以使用 css 将起始编号更改为 0,它会完全按照您的意愿呈现。您甚至可以dot将数字后面的更改为" - ",然后问题就解决了。

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

the above will render as:

以上将呈现为:

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


the Mustache.js way to do it

Mustache.js 方法

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.

如果您想在 mustache 中执行此操作,正确的方法是将字符串数组转换为对象数组,其中存在索引和字符串值。

// 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","stackoverflow","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);

回答by rnella01

If you can use handlebars.js, then you can use the partial mentioned in this gist: https://gist.github.com/1048968

如果你可以使用handlebars.js,那么你可以使用这个gist中提到的部分:https: //gist.github.com/1048968

Ref: In Mustache, How to get the index of the current Section

参考:在 Mustache 中,如何获取当前部分的索引

回答by Tayyab

If you want to access the index multiple times per item, I would suggest something like the following.

如果您想对每个项目多次访问索引,我会建议如下。

var data = {
    items: [{
        name: Aliasghar
        , grade: 19
    }, {
        name: Afagh
        , grade: 20
    }]
    , setUpIndex: function() {
        ++window['INDEX']||(window['INDEX']=0);
        return;
    }
    , getIndex: function() {
        return window['INDEX'];
    }
    , resetIndex: function() {
        window['INDEX']=null;
        return;
    }
}
  • Use the restIndexfunction before iterating each list in Mustache.
  • Use the setUpIndexfunction at the start of each list item to set up the index for that item.
  • Use the getIndexitem to access the index.
  • restIndex在迭代 Mustache 中的每个列表之前使用该函数。
  • 使用setUpIndex每个列表项开头的函数来设置该项的索引。
  • 使用该getIndex项目访问索引。

As an example, consider this.

作为一个例子,考虑这个。

{{resetIndex}}
{{#items}}
    {{setUpIndex}}
    {{getIndex}}. {{name}} is at index {{getIndex}}
{{/items}}

Notice how you can access index more than once per item without getting the wrong value.

请注意如何为每个项目多次访问索引而不会得到错误的值。

回答by Steve Cooper

(Tested in node 4.4.7, moustache 2.2.1.)

(在节点 4.4.7、mustache 2.2.1 中测试。)

If you want a nice clean functional way to do it, that doesn't involve global variables or mutating the objects themselves, use this function;

如果您想要一种简洁的函数式方法来实现它,不涉及全局变量或改变对象本身,请使用此函数;

var withIds = function(list, propertyName, firstIndex) {
    firstIndex |= 0;
    return list.map( (item, idx) => {
        var augmented = Object.create(item);
        augmented[propertyName] = idx + firstIndex;
        return augmented;
    })
};

Use it when you're assembling your view;

在组装视图时使用它;

var view = {
    peopleWithIds: withIds(people, 'id', 1) // add 'id' property to all people, starting at index 1
};

The neat thing about this approach is that it creates a new set of 'viewmodel' objects, using the old set as prototypes. You can read the person.idjust as you would read person.firstName. However, this function doesn't change your people objects at all, so other code (which might have relied on the ID property not being there) will not be affected.

这种方法的巧妙之处在于它创建了一组新的“viewmodel”对象,使用旧的集合作为原型。您可以像阅读person.id一样阅读person.firstName。但是,此函数根本不会更改您的人员对象,因此其他代码(可能依赖于不存在的 ID 属性)不会受到影响。

回答by Elaine

You can use Handlerbars.js, then

你可以使用Handlerbars.js,然后

Handlebars.registerHelper("inc", function (value, options) {
    return parseInt(value) + 1;
});

To use it in HTML

在 HTML 中使用它

{{inc @@index}}