简体   繁体   中英

Rendering a nested model handlebars?

I have a data structure like this.

var myModel {
    _id: 798698,
    username: "John",
    message: {
        message1: "Some cool messsage",
        message2: "I'm mad Ohio State lost"
    }
}

The message object is a little tricky. Inside my handlebars template.

{{#each message}}
    <div class="message">
        {{../username}}: {{this}}
    </div>
{{/each}}

Then when that renders the output is something like this.

<div class="NCAA">
    <div class="NBA">
        <div class="message">steve: What?</div>
        <div class="message">steve: Okay?</div>
        <div class="message">steve: Hey</div>
    </div>

    <div class="NBA"></div>

    <div class="NBA">
        <div class="message">
            Iowastate: Hey nikeman
        </div>
    </div>
</div>

The class names come from a backbone view, but the problem is the template is being wrapped by a div and I am not sure how to prevent that so that its just a list of .message .. Also I cant identify why there is an empty div, I have suspicions but cant point my finger to it..

Here is the backbone view code, just to show you how things are rendered.

var Marionette = require('backbone.marionette');

var ChatView = Marionette.ItemView.extend({
    className: 'NBA',
    template: require('../../templates/message.hbs')
});

module.exports = CollectionView = Marionette.CollectionView.extend({
    className: 'NCAA',
    initialize: function() {
        this.listenTo(this.collection, 'change', this.render);
    },
    itemView: ChatView
});

In Backbone, every view is associated with an el. At the time of instantiation, if you do not provide an el for the view, backbone uses an empty DIV. I guess this is what is happening in your case.

So at the time of your view instantiation, just provide an el element like this:

var myView = new ChartView({ el: $('.myElementForView') })

Read this text from Backbone View el documentation

All views have a DOM element at all times (the el property), whether they've already been inserted into the page or not. In this fashion, views can be rendered at any time, and inserted into the DOM all at once, in order to get high-performance UI rendering with as few reflows and repaints as possible. this.el is created from the view's tagName, className, id and attributes properties, if specified. If not, el is an empty div.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM