0

I was writing a small template like this:

var viewHelpers = {
  valExists: function (variable) {
    var exists = ((typeof variable == "string") && (variable != ""));
    console.log('variable exists: ', exists, ' value: ', variable);
    return exists;
  },
}

var tpl = '<h1>Hello <%- _.find(["a", "b"], _.valExists) %></h1>';
_.extend(data, viewHelpers);
console.log(_.template(tpl, {
  data: data,
}));

I'd expect the template to return '<h1>Hello a</h1>'.

Instead, Firefox display this error:

TypeError: t is undefined

What's wrong?

1 Answer 1

1

I understand it incorrectly. And I now found my solution.

The problem above occurs when the function is not found in _ object. And viewHelpers are not meant to be bind to the _ object at all. They should just be part of the data providing to template.

My code should looks something like this:

var tpl = '<h1>Hello <%- _.find(["a", "b"], valExists) %></h1>';

var datalist = {
    data: data,
    valExists: function (variable) {
        var exists = ((typeof variable == "string") && (variable != ""));
        console.log('variable exists: ', exists, ' value: ', variable);
        return exists;
    },
    printExists: function (variables) {
        return _.find(variables, valExists);
    }
}

console.log(_.template(tpl, datalist));

These viewHelpers are actually living in the same namespace as other variables in datalist.

To make it looks better, I could separate the definition of viewHelper from the datalist:

var tpl = '<h1>Hello <%- _.find(["a", "b"], valExists) %></h1>';

var viewHelpers = {
    valExists: function (variable) {
        var exists = ((typeof variable == "string") && (variable != ""));
        console.log('variable exists: ', exists, ' value: ', variable);
        return exists;
    },
    printExists: function (variables) {
        return _.find(variables, valExists);
    }
}

var datalist = {
    data: data,
}

// add the viewHelpers definition to datalist
_.extend(datalist, viewHelpers);

//
console.log(_.template(tpl, datalist));

They are practically the same.

My error occurs when my viewHelpers do not exists in the data provided to template.

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.