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

How to iterate on attribute of an object in handlebar

{
  user: {
  photos: ['a','b']
    }
}

如何迭代 photos。 像这样

{{#each user.photos}}
   <span>{{this}}</span>
{{/each}}

确保:

  1. 检查模板是否存在于您的 HTML:
<script id="user-photos-template" type="text/x-handlebars-template">
{{#each user.photos}}
  <span class="user-photo">{{this}}</span>
{{/each}}
</script>
  1. 编译模板:
const template = (sel) => Handlebars.compile(document.querySelector(sel).innerHTML);
const userPhotosTemplate = template('#user-photos-template');
  1. 设置渲染数据的HTML文本:
document.getElementById('result').innerHTML = userPhotosTemplate(userData);

例子

const template = (sel) => Handlebars.compile(document.querySelector(sel).innerHTML);
const userPhotosTemplate = template('#user-photos-template');
const userData = {
  user: {
    name: 'Bob',
    photos: ['a', 'b', 'c']
  }
};

document.getElementById('result').innerHTML = userPhotosTemplate(userData);
.user {
  display: flex;
  flex-direction: column;
  justify-content: center;
  width: 10em;
  height: 10em;
  border: thin solid grey;
}

.user .user-name {
  font-weight: bold;
  text-align: center;
  margin-top: 0.25em;
}

.user .user-photos {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: center;
  flex: 1;
}

.user .user-photos .user-photo {
  width: 3em;
  height: 3em;
  line-height: 3em;
  margin: 0.5em;
  border: thin solid grey;
  text-align: center;
  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">
  <div class="user-name">{{user.name}}</div>
  <div class="user-photos">
  {{#each user.photos}}
     <span class="user-photo">{{this}}</span>
  {{/each}}
  </div>
</div>
</script>