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

时间:2015-06-12 09:20:22

标签: javascript templates underscore.js underscore.js-templating

我会创建一个用于生成其他模板的主模板。我发现的唯一方法就是这个:

var test_tpl_master = _.template(
    "StackOverflow <%= 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 %>"
}));

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

1 个答案:

答案 0 :(得分:3)

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

例如,让我们说你有

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/