【问题标题】:Handlebars.js access nested array values by variableHandlebars.js 通过变量访问嵌套数组值
【发布时间】:2018-10-03 04:11:31
【问题描述】:

我有一个嵌套对象,所有索引都是时间戳,它包含有关时间戳日期和当天事件的信息

data : {
    1522620000:  {
        events: {
           1522620940: {title: event1},
           1522620970: {title: event2},
        }
    },
    1522706400:
        events: {
           1522620940: {title: event4},
           1522620970: {title: event6},
        }
    },
    1523311200: {
        events: {}
    },
    ...
}

如何在不循环访问数组的情况下访问星期五的所有事件? 我只有时间戳1522706400 表示为变量timestamp,我想像data[timestamp].events 一样访问它

目前我有

{{#each day}} //<-- another variable from a calendar.. don't care about it
    {{# each data[timestamp].events }} //<-- the day contains information about the timestamp but does not contain the events..
        {{ title }}
    {{/each}}
{{/each}}

我通常使用 AngularJS 来完成类似的事情,但我有一个客户希望我使用车把,我对此感到非常困惑。

【问题讨论】:

    标签: javascript handlebars.js


    【解决方案1】:

    我能够自己解决它。我创建了以下Helper

    Handlebars.registerHelper("getNestedValue", function(obj, options) {
        var context,
            response = "";
        var timestamp = options.hash.key;
    
        if(typeof obj[timestamp] !== 'undefined'){
            var data = obj[timestamp]; // <-- all information for the timestamp
            $.each(data.events, function (index, item) { // <-- loop through all events
                context = item;
                response += options.fn(context); // <-- include the variable to the template
            });
    
        }
    
        return response;
    });
    

    所以我可以像访问它一样访问它

    {{#getNestedValue  ../data key=timestamp }}
        <li class="icon-calendar-events-16">
            <a href="{{ url }}">
                {{ title }}
            </a>
            <small>{{ location }}</small>
        </li>
    {{/getNestedValue}}
    

    【讨论】:

      猜你喜欢
      • 2020-04-25
      • 2022-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多