HBS: Template array of objects
Loop through an array of objects.
by kyllle
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-alpha1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.5/handlebars.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.3.3/backbone-min.js"></script>
<script type="text/x-handlebars-template" class="template">
<p>Errors:</p>
<ul class="flush">
{{#each .}}
{{#each this}}
<li>{{this.name}}</li>
<li>{{this.type}}</li>
{{/each}}
{{/each}}
</ul>
</script>
SCSS
* {
-webkit-font-smoothing: antialiased;
}
body {
padding: 5%;
}
JavaScript
console.clear();
var errors = [{
name: 'Question 1: This is a required field',
type: 'test'
}, {
name: 'Question 2: Only numbers allowed',
type: 'test'
}, {
name: 'Question 3: Maximum 30 characters',
type: 'test'
}, {
name: 'Question 4: Please enter a valid email address',
type: 'test'
}];
errors.forEach(function(error, index) {
console.log(error[index]);
});
var ErrorsView = Backbone.View.extend({
className: 'alert alert--error',
template: Handlebars.compile($('.template').html()),
initialize: function(options) {
this.errors = options.errors;
console.log(this.errors);
},
render: function() {
this.model = new Backbone.Model()
this.model.set('errors', this.errors)
this.model.set('isHome', true)
console.log('this.model.toJSON()', this.model.toJSON())
this.$el.html(this.template(this.model.toJSON()));
return this;
}
});
var errorsView = new ErrorsView({
errors: errors
});
$("body").html(errorsView.render().el);