Koala Yeung
Koala Yeung

Reputation: 7843

TypeError using underscore.js template with _.find

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?

Upvotes: 0

Views: 861

Answers (1)

Koala Yeung
Koala Yeung

Reputation: 7843

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.

Upvotes: 1

Related Questions