Search code examples
javascriptbackbone.jsunderscore.js

Rendering Backbone.js view with template variable undefined in the model


Is it possible from a backbone.js view to render an underscore.js template with a variable that is not defined in the related Backbone.js model?

take the can't find variable: username error.

the template to be rendered:

<div class="content" id="content">               
<div id="form">
    <form action="">
        <input id="username" type="text" placeholder="Username" name="username" value= <%=username%> >
        <input id="password" type="password" placeholder="Password" name="password" >
        <ul class="table-view">
            <li class="table-view-cell">
                Remember me
                <div class="toggle active">
                    <div class="toggle-handle"></div>
                </div>
            </li>
        </ul>
        <button id="logbtn" class="btn btn-primary btn-block">Login</button>
    </form>    

<button id="renregbtn" class="btn btn-positive btn-block">Register</button>
</div>
</div>

rendering line from the view:

this.$el.html( this.template_login( this.loginModel ) );

line form the loginModel model file:

define([
    'underscore',
    'backbone',
    ],
    function(_, Backbone) {
        var LoginModel = Backbone.Model.extend({

            urlRoot: '/login',
            initialize: function(){
                this.fetch();
            },
        });

        return LoginModel;
});

I set the model manually. But still take the can't find variable error as in the first render case.

same model above:

define([
    'underscore',
    'backbone',
    ],
    function(_, Backbone) {
        var LoginModel = Backbone.Model.extend({

            urlRoot: '/login',
            defaults: {
                username: "abc",
            },
            initialize: function(){
                this.fetch();
            },
        });

        return LoginModel;
});

Both cases result in:

ReferenceError: Can't find variable: username

Only if I give an hardcoded model json into the template_login it works.

this.$el.html( this.template_login(  {username: "Joe"} ) );

Solution

  • The problems here were in two places. In the model code and in the rendering view code:

    First, model should have defined the variables used in the template, at least by defaults as null.

    Second, rendering code in the view should mention the model's attributes in the template function defined in the same view but not only the model.

    Like so:

    First,

    in model file:

    defaults: {
                username: "",//or alternately username: null,
            },
    

    Second

    in view file:

    this.$el.html( this.template_login( this.loginModel.attributes ) );