R
R
rakro2015-08-27 19:47:04
backbone.js
rakro, 2015-08-27 19:47:04

Different templates in backbone.js?

New to backbone. We need to quickly figure out the next question. Is it possible to use different templates for the same model, depending on the model attribute? For example field online == true? draw one template, false another.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
C
Cat Anton, 2015-08-27
@rakro

In general, it is possible.

var ModelView = Backbone.View.extend({
    // ...

    render: function() {
        var $template = this.model.get('online') ? $('#template1') : $('#template2');
        var template = _.template($template.html());
        this.$el.html(template(this.model.toJSON()));
        return this;
    }
});

But in most cases, it makes more sense to create two different views, each with its own template, its own events, etc.

K
Konstantin Kitmanov, 2015-08-28
@k12th

I would just do an if in the template :)

A
Alexander Prozorov, 2015-09-02
@Staltec

The question was posed incorrectly. Templates should not be directly related to the Model at all. They refer to views (View). It would be correct, depending on the state of the model attribute, to render the corresponding view. Juggling different templates in one view is a crutch that may very soon require refactoring if your functionality of these views starts to differ greatly.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question