Mike O.
Mike O.

Reputation: 1045

How to iterate on attribute of an object in handlebar

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

How do you iterate over photos. Something like this

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

Upvotes: 0

Views: 44

Answers (1)

Mr. Polywhirl
Mr. Polywhirl

Reputation: 48733

Make sure to:

  1. Check if the template exists in your HTML:
<script id="user-photos-template" type="text/x-handlebars-template">
{{#each user.photos}}
  <span class="user-photo">{{this}}</span>
{{/each}}
</script>
  1. Compile the template:
const template = (sel) => Handlebars.compile(document.querySelector(sel).innerHTML);
const userPhotosTemplate = template('#user-photos-template');
  1. Set the HTML text of the rendered data:
document.getElementById('result').innerHTML = userPhotosTemplate(userData);

Example

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>

Upvotes: 1

Related Questions