Search code examples
javascripthtmlmarionette

Marionette.js showing CollectionView


I am a beginner in Marionette and trying to get a view output to be like this:

<div class="style_title">Component Library</div>
<ul class="style_content">
    <li class="style_item">title1</li>
    <li class="style_item">title2</li>
</ul>

This is ItemView and CollectionView:

var TitleView = Marionette.ItemView.extend({
       template: _.template("<%=title%>"),
       tagName: "li",
       className: "style_item"
    });

    var TitleListView = Marionette.CollectionView.extend({
        tagName: "ul", 
        className: "style_content",
        initialize: function() {
            this.collection = new Backbone.Collection();
            ComponentService.getComponents().forEach(function (title) {
                this.collection.add(title);
            }.bind(this));
        },
        childView: TitleView  
    });

How to add div attribute to get a needed output. There is a possibility to use text!js, but I can't get things together. Thank you in advance.


Solution

  • You can use CompositeView instead of Collection view in which you can pass template not just set a tag and specify container for items.

    var TitleListView = Marionette.CompositeView.extend({
        template: _.template('<div class="style_title">Component Library</div><ul class="style_content"></ul>'),
        childViewContainer: 'ul.style_content',
        initialize: function() {
            this.collection = new Backbone.Collection();
            ComponentService.getComponents().forEach(function (title) {
                this.collection.add(title);
            }.bind(this));
        },
        childView: TitleView
    });
    

    Actually in the next versions of Marionette they plan to remove CompositeView and allow to pass template to CollectionView.