0

Is it possible to use underscore.js with Mustache style function calls? The underscore.js manual has an example how to support Mustache syntax:

_.templateSettings = {
  interpolate : /\{\{(.+?)\}\}/g
};

var template = _.template("Hello {{ name }}!");
template({name : "Mustache"});
=> "Hello Mustache!"

However, apart from variables mustache.js also automatically detects when the object is a function and then evaluates it. From the mustache.js manual:

var view = {
  title: "Joe",
  calc: function () {
    return 2 + 4;
  }
};

var output = Mustache.render("{{title}} spends {{calc}}", view);

However, using underscore.js to render the latter results in:

var template = _.template("{{title}} spends {{calc}}");
template(view);
"Joe spends function () {
    return 2 + 4;
}"
4

2 回答 2

0

Underscore's template function doesn't perform type checking and always returns the value of the property/variable.

https://github.com/documentcloud/underscore/blob/master/underscore.js#L1161

But you can use the underscore template evaluate block to run javascript functions.

So you can do the following:

var template = _.template("<% var spend = calc() %>{{title}} spends {{ spend }}");

That's obviously using the default ERB-style evaluation block, so feel free to write your own regex for evaluate in _.templateSettings if you'd rather use a different syntax.

于 2013-04-17T00:14:50.737 回答
0

The simplest way is to evaluate the function, since Underscore allows arbitrary JavaScript inside the template block.

var template = _.template("{{title}} spends {{calc()}}");
于 2013-05-01T02:30:55.953 回答