× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

Not sure how to template object of arrays using Backbone and Underscore templates

Yuriy Linnyk
Apr 06, 2016
<ol> <li>You are not even calling <code>render()</code>, so your template is never even executed, and the <code>object Object</code> output has nothing to do to your template.</li> <li>After you run <code>render()</code> you will realize<br> <code>template: '.js-department'</code><br> doesn't work, because it is not Marionette, and Backbone will not compile the html by a selector for you. So you will replace it with something like this:<br> <code>template: _.template($('.js-department').html())</code></li> <li>Then you will have to realize <code>this.collection</code> is an array, that only has one item, so if you just want to render that first item, you will send to it to template:<br> <code>this.$el.html( this.template( this.collection.first().toJSON() ) );</code></li> <li>Then you will have to realize <code>departmentView</code> is a Backbone.View instance object, and isn't html itself. It has the <code>el</code> property which is the DOM element of this view instance, and <code>$el</code> property, which is the same DOM element wrapped with jQuery.</li> <li><code>document.body.innerHTML = departmentView.el</code> still will not work, because <code>innerHTML</code> expects a string. So you could instead do something like<br> <code>document.body.appendChild( departmentView.el );</code> or<br> <code>departmentView.$el.appendTo( document.body );</code> with jquery.<br> (For the last one to work <code>render</code> must <code>return this</code>)</li> </ol> <p>Working jsfiddle: <a href="http://jsfiddle.net/yuraji/zuv01arh/" rel="nofollow">http://jsfiddle.net/yuraji/zuv01arh/</a></p> <p>This tip was originally posted on <a href="http://stackoverflow.com/questions/33572366/Not%20sure%20how%20to%20template%20object%20of%20arrays%20using%20Backbone%20and%20Underscore%20templates/33574156">Stack Overflow</a>.</p>
comments powered by Disqus