如何迭代车把中对象的属性

{

  user: {

  photos: ['a','b']

    }

}


你如何迭代photos. 像这样的东西


{{#each user.photos}}

   <span>{{this}}</span>

{{/each}}


长风秋雁
浏览 63回答 1
1回答

小唯快跑啊

确保:检查您的 HTML 中是否存在该模板:<script id="user-photos-template" type="text/x-handlebars-template">{{#each user.photos}}&nbsp; <span class="user-photo">{{this}}</span>{{/each}}</script>编译模板:const template = (sel) => Handlebars.compile(document.querySelector(sel).innerHTML);const userPhotosTemplate = template('#user-photos-template');设置渲染数据的 HTML 文本:document.getElementById('result').innerHTML = userPhotosTemplate(userData);例子const template = (sel) => Handlebars.compile(document.querySelector(sel).innerHTML);const userPhotosTemplate = template('#user-photos-template');const userData = {&nbsp; user: {&nbsp; &nbsp; name: 'Bob',&nbsp; &nbsp; photos: ['a', 'b', 'c']&nbsp; }};document.getElementById('result').innerHTML = userPhotosTemplate(userData);.user {&nbsp; display: flex;&nbsp; flex-direction: column;&nbsp; justify-content: center;&nbsp; width: 10em;&nbsp; height: 10em;&nbsp; border: thin solid grey;}.user .user-name {&nbsp; font-weight: bold;&nbsp; text-align: center;&nbsp; margin-top: 0.25em;}.user .user-photos {&nbsp; display: flex;&nbsp; flex-direction: row;&nbsp; flex-wrap: wrap;&nbsp; justify-content: center;&nbsp; flex: 1;}.user .user-photos .user-photo {&nbsp; width: 3em;&nbsp; height: 3em;&nbsp; line-height: 3em;&nbsp; margin: 0.5em;&nbsp; border: thin solid grey;&nbsp; text-align: center;&nbsp; text-transform: uppercase;}<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.7.6/handlebars.min.js"></script><div id="result"></div><script id="user-photos-template" type="text/x-handlebars-template"><div class="user">&nbsp; <div class="user-name">{{user.name}}</div>&nbsp; <div class="user-photos">&nbsp; {{#each user.photos}}&nbsp; &nbsp; &nbsp;<span class="user-photo">{{this}}</span>&nbsp; {{/each}}&nbsp; </div></div></script>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript