HBS: Template array of objects
Loop through an array of objects.
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">
{{#errors[0]}}
{{#each this}}
<li>{{this}}</li>
{{/each}}
{{/errors}}
</ul>
</script>
SCSS
* {
-webkit-font-smoothing: antialiased;
}
body {
padding: 5%;
}
JavaScript
console.clear();
var errors = [{
0: 'Question 1: This is a required field'
}, {
1: 'Question 2: Only numbers allowed'
}, {
2: 'Question 3: Maximum 30 characters'
}, {
3: 'Question 4: Please enter a valid email address'
}];
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.$el.html(this.template({
errors: this.errors
}));
return this;
}
});
var errorsView = new ErrorsView({
errors: errors
});
$("body").html(errorsView.render().el);