Jamie Hutber
Jamie Hutber

Reputation: 28064

Underscore template not getting values?

So, I am having difficulties getting my object's data into my underscore template.

JS

var details = SD.defaultView.extend({
    el: 'page',
    template: JST['app/www/js/templates/sex.ejs'],
    information: {
        header: 'some information!!!',
        image: '/img/path.jpg'
    },
    render: function () {
        var infom = _.template(this.template(), this.information);
        c(_.template(this.template()).source);
        this.$el.html(infom);
    }
});

JST Template

<% console.info(this.information); %>
<sexform></sexform>

Console Output

Object { header="some infromatoin!!!", image="/img/path.jpg"} global.js (line 34)
Object { header="some infromatoin!!!", image="/img/path.jpg"} global.js (line 34)

//output of c(_.template(this.template()).source);
function(obj){
var __t,__p='',__j=Array.prototype.join,print=function(){__p+=__j.call(arguments,'');};
with(obj||{}){
__p+='<sexform></sexform>';
}
return __p;
}

Now, as you can see the object is getting passed via this but intresting if i try this:

 <% c(this.information.header); %>
 <sexform></sexform>

with the following error:

TypeError: this.information is undefined  templates.js (line 21)
...__e = _.escape, __j = Array.prototype.join;function print() { __p += __j.call(ar...

This, should 100% work with the dot notation.

Upvotes: 0

Views: 875

Answers (1)

KiT O
KiT O

Reputation: 867

That's because data is undefined! you are passing this.data not {data: this.data}, therefore argument of template is {header: '..', image: '..'}

correct code is :

var wank = SD.defaultView.extend({
    el: 'page',
    template: JST['app/www/js/templates/sex.ejs'],
    data: {
        header: 'interesting!!!',
        image: '/img/path.jpg'
    },
    render: function () {
        // this line is changed
        var infom = _.template(this.template(), {data: this.data});
        this.$el.html(infom);
    }
});

Edit

template: JST['app/www/js/templates/sex.ejs'] is compiled template, so :

var infom = _.template(this.template(), {data: this.data});

is wrong and it must be

var infom = _.template({data: this.data});

Upvotes: 4

Related Questions