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

前端 未结 13 1119
臣服心动
臣服心动 2020-12-13 03:52

I am using Mustache and using the data

{ \"names\": [ {\"name\":\"John\"}, {\"name\":\"Mary\"} ] }

My mustache template is:



        
13条回答
  •  孤街浪徒
    2020-12-13 04:15

    (Tested in node 4.4.7, moustache 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.id just 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.

    Algorithm is O(N), so nice and fast.

提交回复
热议问题