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.