javascripttemplatesunderscore.jsjst

How to use JST with underscore.js?


I'm having troubles using variables that would normally be no problem with understand.js, but seemingly when you combine JST with underscore.js it seems to struggle.

var something= SD.defaultView.extend({
    el: 'page',
    template: JST['app/www/js/templates/sex.ejs'],
    data: {
        header: 'some information!!!',
        image: '/img/path.jpg'
    },
    render: function () {
        var compiled = _.template(this.template(), this.data); //I pass in the complied JST template
        this.$el.html(compiled);
    }
});

JST File rendered

this["JST"]["app/www/js/templates/sex.ejs"] = function (obj) {
    obj || (obj = {});
    var __t, __p = '', __e = _.escape;
    with (obj) {
        __p += ((__t = ( header )) == null ? '' : __t) + '<sexform>Hello There</sexform>';
    }
    return __p
};

Error

ReferenceError: header is not defined - templates.js (line 21)

...obj = {});var __t, __p = '', __e = _.escape;with (obj) {__p +=((__t = ( header )...

sex.ejs

<%= header %><sexform>Hello There</sexform>

Background Information

As expected, header is not available at the time of the reader, which is happening via grunt file with each change to my JST templates. I feel I must be implement JST's the wrong way.

But, to me this seems like the correct way of doing everything.

Of course, I am trying to use variables with underscore inside of sex.ejs

All of this code can be seen here: http://m.sexdiaries.co.uk/#wank NB: I can assure that this is safe for work and contains no images, even though as misleading as the url is its really not adult material, its an educational app.


Solution

  • You have this to define the view's template:

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

    And JST contains functions (which is, more or less, the whole point of using JST-style precompiled templates):

    this["JST"]["app/www/js/templates/sex.ejs"] = function (obj) {
    

    Then you do this:

    var compiled = _.template(this.template(), this.data);
    // function call ----------------------^^
    

    Two things are wrong there:

    1. You've already called _.template to compile the template.
    2. this.template is the compiled template function that expects to be fed this.data.

    The fix is quite simple:

    var compiled = this.template(this.data);