when passing a variable into a backbone template, how to reference it in the template?

40,269

Solution 1

Underscore's _.template:

Compiles JavaScript templates into functions that can be evaluated for rendering.
[...]

var compiled = _.template("hello: <%= name %>");
compiled({name : 'moe'});
=> "hello: moe"

So basically, you hand the template function an object and the template looks inside that object for the values you use in your template; if you have this:

<%= property %>

in your template and you call the template function as t(data), then the template function will look for data.property.

Usually you convert the view's model to JSON and hand that object to the template:

render: function (eventName) {
    $(this.el).html(this.template(this.model.toJSON()));
    return this;
}

I don't know what your eventName is or what you're planning to do with it but you need to get an object with this structure:

data = { id: '...', emailId: '...', status: '...' }

from somewhere and hand that to the template function:

var html = this.template(data)

to get some HTML to put on the page.

Demo (with a fake model for illustrative purposes): http://jsfiddle.net/ambiguous/hpSpf/

Solution 2

OptionalExtrasView = Backbone.View.extend({
    initialize: function() {
        this.render();
    },
    render: function() {
        // Get the product id
        //var productid = $( this ).attr( "productid" );
        var data = {name : 'moe'};

        var tmpl = _.template($('#pddorder_optionalextras').html() );
        this.$el.html(tmpl(data));
    }
});

   var search_view = new OptionalExtrasView({ el :     $('.pddorder_optionalextras_div')});

and just before the body tag:

      <script type="text/template" id="pddorder_optionalextras">
   <%= name %>
    </script> 
Share:
40,269
Nambi
Author by

Nambi

Java, Android, REST, MySQL, Linux, Maven, Perl, Javascript, html, SQL.

Updated on February 08, 2020

Comments

  • Nambi
    Nambi about 4 years

    the Template looks like this.

    <div>
        <H5>Status for your request</H5>
        <table>
        <tbody>
        <tr>
            <th>RequestId</th>
            <th><%=id%></th>
        </tr>
        <tr>
            <th>Email</th>
            <th><%=emailId%></th>
        </tr>       
        <tr>
            <th>Status</th>
            <th><%=status%></th>
        </tr>       
         </tbody>
         </table>
    </div>
    

    This is the View Javascript that renders the page.

    window.StatusView = Backbone.View.extend({
    
    initialize:function () {
        console.log('Initializing Status View');
        this.template = _.template(tpl.get('status'));
    },
    
    render:function (eventName) {
    
        $(this.el).html(this.template());
        return this;
    },
    
    events: { "click button#status-form-submit" : "getStatus" },
    
    getStatus:function(){
    
        var requestId = $('input[name=requestId]').val();
        requestId= $.trim( requestId );
    
        var request  = requests.get( requestId );
    
        var statusTemplate = _.template(tpl.get('status-display'));
        var statusHtml = statusTemplate( request );
        $('#results-span').html( statusHtml );
    }
    
    });
    

    When the clicks on the input, the requestId is read and the status is appended in html element with id 'results-span'.

    The failure happens when replacing the values in html-template with variable values.

    var statusTemplate = _.template(tpl.get('status-display'));
    var statusHtml = statusTemplate( request );
    

    The rendering fails with the following error.

    Uncaught ReferenceError: emailId is not defined
    (anonymous function)
    _.templateunderscore-1.3.1.js:931
    window.StatusView.Backbone.View.extend.getStatusstatus.js:34
    jQuery.event.dispatchjquery.js:3242
    jQuery.event.add.elemData.handle.eventHandle
    
  • Nambi
    Nambi about 12 years
    Thank you for the pointers. Instead of passing the Backbone model, I passed a pure javascript object that is created from the model. var data = { id : request.get('id'), emailId : request.get('emailId'), status : request.get('status') }; . Now template is rendering it fine. What is the difference between BackBone model and pure JS object?
  • mu is too short
    mu is too short about 12 years
    @Nambi: Views usually display models or collections in Backbone and that model or collection is in this.model or this.collection. Then you translate the model/collection to a plain JavaScript data structure using the toJSON method. If request is a Backbone model then your var data = { ... } is the same as var data = request.toJSON() except that toJSON will include all the request attributes. The template does care, it just wants an object with the right keys.
  • Alexander Mills
    Alexander Mills about 9 years
    I get this using Node.js, Error message is----> name is not defined
  • Alexander Mills
    Alexander Mills about 9 years
    I think this is because I should be using EJS templating not underscore templating