Search⌘ K
AI Features

Building a CompositeView

Explore how to build a CompositeView in Marionette.js to render a collection of contacts inside a styled table. Understand modifying templates for table rows, adding column headers, and configuring childView containers for dynamic content display.

Now that we’ve done some house cleaning in our codebase, let’s display our contacts within a table. We already have our contacts in a collection, so we simply need to render a tr DOM element for each one of them.

Creating a template for a table row

Let’s modify the contact template to make it generate the contents for a table row:

PHP
<script type="text/template" id="contact-list-item">
<td><%- firstName %></td><td><%- lastName %></td>
</script>

We need our table row to be wrapped within a tr tag, so let’s modify line 2 in the Contact view:

Node.js
List.Contact = Marionette.ItemView.extend({
tagName: "tr",
template: "#contact-list-item",
// event-handling code is here
});

Lastly, we need our Contacts view to be contained within a table instead of the current ul tag. Let’s edit line 2 to change the tag:

Node.js
List.Contacts = Marionette.CollectionView.extend({
tagName: "table",
className: "table table-hover",
childView: List.Contact
});
...