Benjamin Dean
Benjamin Dean

Reputation: 769

Function undefined inside Underscore.js template

I have some Underscore.js template that renders completely fine, except, the function called inside that template is undefined. For example:

<span class='<% checkClass(oldValue, newValue) %>'>

The function itself works completely fine outside the template and returns the class name as expected. Does Underscore templates have their our scope?

UPD: That's how template is defined and called:

function checkClass() {... return 'Something' ...}

pData = [Object]; //Just for reference

var rowsTpl = _.template("<span class='<% checkClass(oldValue, newValue) %>'>");

_.each(pData, function (vals, name) {

    prOutput = rowsTpl(vals);

    $(this.elem).html(prOutput);

});

Upvotes: 1

Views: 519

Answers (1)

Benjamin Dean
Benjamin Dean

Reputation: 769

Just figured out (as I think) the right way. In my case, I have to pass my own object to template, including the needed functions or data:

var rowsTpl = _.template("<span class='<% func.checkClass(val.oldValue, val.newValue) %>'>");

Notice, that I am accessing checkClass function from func object and oldValue and newValue from val object. Here is the declaration:

_.each(pData, function (vals, name) {

    outPut += rowsTpl({
        name: name,
        val: vals,
        func: {
            checkClass: checkClass,
            anyOtherThing: thing
        }
    });

});

Upvotes: 1

Related Questions