Handlebars渲染多对象时无法获取list_of_date内日期与type字段问题
Handlebars嵌套数据读取问题解决方案
问题根因
- 模板遍历层级错误:
list_of_date是单个用户对象下的属性,原有模板将其放在{{#users}}块外读取,对应层级不存在该属性 - 未处理多层嵌套结构:
list_of_date为数组,内部元素是「日期为键、内容数组为值」的对象,需要多层遍历才能拿到日期和type字段
修改后的模板代码
<script id="document-template" type="text/x-handlebars-template"> <div> {{#each this}} {{#each users}} <!-- 遍历每个用户 --> {{#each list_of_date}} <!-- 遍历用户下的list_of_date数组 --> {{#each this}} <!-- 遍历日期对象,@key对应日期字符串,this对应该日期的内容数组 --> {{#each this}} <!-- 遍历内容数组拿到type字段,通过../回退上层上下文读取name和日期 --> {{../name}} {{@../key}} {{type}} {{/each}} {{/each}} {{/each}} {{/each}} {{/each}} </div> </script>
完整可运行代码
<!DOCTYPE html> <html> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/1.0.0/handlebars.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> </head> <body> <div id="DocumentResults"></div> <script id="document-template" type="text/x-handlebars-template"> <div> {{#each this}} {{#each users}} {{#each list_of_date}} {{#each this}} {{#each this}} {{../name}} {{@../key}} {{type}} {{/each}} {{/each}} {{/each}} {{/each}} {{/each}} </div> </script> <script> $(function() { var source = $("#document-template").html(); var template = Handlebars.compile(source); var html = template(data); $('#DocumentResults').html(html); }); var data = [{ users: [{ name: 'Eric', list_of_date: [{ "2019-01-01": [{ "id": "1", "type": "Eric Type a", }], "2019-12-31": [{ "id": "2", "type": "Eric Type b", }] }], }, { name: 'Alan', list_of_date: [{ "2020-01-01": [{ "id": "1", "type": "Alan Type a", }] }], }] }]; </script> </body> </html>
注:你给出的预期输出里Eric 2019-12-31对应的type标注为Eric Type a,实际原始数据中该条为Eric Type b,运行后输出会和原始数据保持一致,若要匹配预期可自行修改数据里的对应字段。
内容的提问来源于stack exchange,提问作者Stacie T.
相关产品推荐
相关产品推荐

