Which component to use to implement a menu?


I want to display a menu like:

Obi Wan Kenobi
  My friends

My lightsabers
  Blue lightsaber
  Green lightsaber 
  Add a lightsaber

As you can see, the My lightsabers menu is a list of items, but the link to add a new lightsaber is independent.

I believe I should use a CollectionView to render the lightsabers list, but how to render the "add" link?

Do you have any example of such menus?

The question can be generalized in: How to customize bits of HTML rendered by Marionette without breaking thing it does?

I'd use a CompositeView for this, because of the need for the add link.

You would set up a template that contains a placeholder for the actual list, and then has the add link and all the necessary other bits as well. Then modify the appendHtml method of the composite view to place the actual items in the correct spot.

For example, here's a template that would get you down the path:

<script id="light-saber-menu-template" type="text/html">
  <h4>My Lightsabers</h4>
  <ul id="light-sabers">
    <li class="divider"></li>
    <li><a href="#">Add A Lightsaber</a></li>

<script id="light-saber-menu-item-view" type="text/html">
  <%= name %>

In this example, I would use the divider ul as the location to put the items, inserting them before the divider:

MenuItem = Backbone.Marionette.ItemView.extend({
  template: "#light-saber-menu-item-template",
  tagName: "li"

MenuView = Backbone.Marionette.CompositeView.extend({
  template: "#light-saber-menu-template",

  itemView: MenuItem,

  appendHtml: function(cv, iv){
    var $divider = cv.$(".divider");

myLightSabers = new LightSaberCollection(... data ...);

menu = new MenuView({
  collection: myLightSabers


This should produce a <ul> with the items you expect:

  <h4>My Lightsabers</h4>
    <li class="divider"></li>
    <li><a href="#">Add A Lightsaber</a></li>

For more examples on using a CompositeView, see this blog post: http://lostechies.com/derickbailey/2012/04/05/composite-views-tree-structures-tables-and-more/

This video can help you solving your question :)
By: admin