为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

长风秋雁 2023-11-02 21:56:39
{  user: {  photos: ['a','b']    }}你如何迭代photos. 像这样的东西{{#each user.photos}}   <span>{{this}}</span>{{/each}}
查看完整描述

1 回答

?
小唯快跑啊

TA贡献1863条经验 获得超2个赞

确保:


检查您的 HTML 中是否存在该模板:

<script id="user-photos-template" type="text/x-handlebars-template">

{{#each user.photos}}

  <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 = {

  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>


查看完整回答
反对 回复 2023-11-02
  • 1 回答
  • 0 关注
  • 58 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信