Search⌘ K
AI Features

Listing our Contacts with a CollectionView

Explore how to implement a CollectionView in Marionette.js to display a list of contact models. Learn to create collections, customize item views with tagName for proper HTML structure, and manage rendering without extra wrapper elements.

So, how do we implement this in our app? Let’s display a collection of contacts as an unordered list, i.e., within a ul element.

Transforming JavaScript data into HTML

This is how our JavaScript data will be transformed into HTML via a CollectionView:

Correspondence between JavaScript data and rendered HTML using a CollectionView
Correspondence between JavaScript data and rendered HTML using a CollectionView

First, we’ll need a template and view to display each model:

<script type="text/template" id="contact-list-item">
<li><%- firstName %> <%- lastName %></li>
</script>
ContactManager.ContactItemView = Marionette.ItemView.extend({
template: "#contact-list-item"
});
Defining a template and view for displaying our models

Remember: Templates go in the HTML section, while our views (being JavaScript) need to go within our application’s script tag. ...