如何部分替换 Underscore.js 模板,或如何从模板创建模板

How to partially substitute an Underscore.js template, or how to create a template from a template

我会创建一个主模板来生成其他模板。我找到的唯一方法是这个:

var test_tpl_master = _.template(
    "Whosebug <%= type %> question number <%= num %>"
);

var test_tpl_1 = _.template(test_tpl_master({
    "type": "good", 
    "num": "<%= num %>"
}));

var test_tpl_2 = _.template(test_tpl_master({
    "type": "stupid", 
    "num": "<%= num %>"
}));

有没有更简单优雅的方法?

您可以创建一个函数,作为您主控的代理并填充您想要的变量。

例如,假设您有

var prefill_template = function(tpl, defs) {
    return function(data) {
        return tpl(_.extend({}, data, defs));
    }
}

然后您可以通过

创建您的子模板函数
var test_tpl_1 = prefill_template(test_tpl_master, {
    "type": "good"
});

var test_tpl_2 =  prefill_template(test_tpl_master, {
    "type": "stupid"
});

并将它们用作任何其他模板:

console.log(test_tpl_1({
    num: 1
}));
console.log(test_tpl_2({
    num: 1
}));

还有一个演示 http://jsfiddle.net/nikoshr/qshb1zrx/