1

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);

});
2
  • 1
    Can you please add how you render/call this template? Note: you've to explicitly pass data and functions as object to the template (including any function you may use). Commented Dec 26, 2014 at 12:25
  • Sure, updated in original post. Documentation is, probably, not much clear about it? Can you tell a bit more about it? Is there a way to pass multiple objects? Commented Dec 26, 2014 at 12:32

1 Answer 1

1

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
        }
    });

});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.