Marionette 3 no longer uses CompositeView , so if we want to get something like this:
<div class='collection'> <h3>List Name</h3> <ul> <li>FOO - BAR</li> <li>FOO - BAR</li> <li>FOO - BAR</li> ... </ul> </div>
We must use CollectionView and View with regions.
1 - Templates
We are going to define two patterns, the first of which is the βparentβ and the other for each βchildβ parent.
parentTemplate.html
<div class='collection'> <h3>List Name</h3> <ul></ul> </div>
childTemplate.html
<p>Item <%= value%></p>
2 - Main model and collection
Allows you to define the default model and its collection to populate the list.
const Item = Backbone.Model.extend({}); const Items = Backbone.Collection.extend({ model: Item });
3 - Views
First we need to create a View for our child view, like this:
import ItemViewTemplate from './childTemplate.html'; const ItemChildView = Marionette.View.extend({ template: _.template(ItemViewTemplate), className: 'item-child-view', tagName: 'li'
Secondly, we need to create a CollectionView that controls each child, therefore:
const ItemsCollectionView = Marionette.CollectionView.extend({ tagName: 'ul',
Finally, we need to create a main View that contains parentTemplate.html, and in this we define the area in which we will load the collection of elements, therefore:
import ItemsViewTemplate './parentTemplate.html'; const ItemsView = Marionette.View.extend({ tagName: 'div', className: 'items-view', template: _.template(ItemsViewTemplate), regions: { body: { el: 'ul',
4- The rest of the code
Now we create the instances necessary for this:
const app = new Marionette.Application({ region: '#main' }); // Three simple Items let item1 = new Item({value: 1}); let item2 = new Item({value: 2}); let item3 = new Item({value: 3}); // Put this Items into a Collection of Items let items = new Items([item1, item2, item3]); // Create the main View let itemsView = new ItemsView(); app.showView(itemsView); // Create the CollectionView for the Items let itemsCollectionView = new ItemsCollectionView({ collection: items }); // Load the CollectionView of Items into the region that we specified in the main View itemsView.showChildView('body', itemsCollectionView); app.start();
5- Result
If we run this, we get:
<div class="collection"> <h3>List Name</h3> <ul class="items-collection-view"> <li class="item-child-view"><p>Item1</p></li> <li class="item-child-view"><p>Item2</p></li> <li class="item-child-view"><p>Item3</p></li> </ul> </div>
Hope this helps! Link