【发布时间】:2014-10-08 07:25:58
【问题描述】:
我想在 Underscore 模板和 Backbone 中使用辅助函数。 现在我正在这样做:
查看:
var View = Backbone.View.extend({
// ...
template: getTpl('#b_ezlo', 1),
// ...
render: function(){
this.$el.html( this.template(this.model.toJSON()) );
}
});
模板获取器:
在这里,我通常会返回模板以及辅助函数。
问题是当我执行prepare 时,我无法返回辅助函数,因为它还需要返回模板的其他变量,这会导致undefined getDisabledState:
function getTpl(tpl, options) {
if (!tpl) return;
if (!options) options = null;
var prepare = false;
if (options == 1) {
// this is called on View initialization
// with template: getTpl('#b_ezlo', 1),
options = {};
prepare = true;
}
var viewHelpers = {}
if (tpl == "#b_view") {
console.log("prepare", prepare);
viewHelpers.getDisabledState = function() {
if (typeof options.disabled != "undefined") {
return options.disabled;
} else {
return '';
}
}
}
_.extend(options, viewHelpers);
if (prepare) {
return _.template($(tpl).html());
} else {
return _.template($(tpl).html())(options);
}
}
以及我想使用帮助器的模板(Jade)的一部分:
.icon-block(data-disabled!="<% if (typeof getDisabledState != 'undefined') {getDisabledState()} %>")
我不喜欢这里的是if (typeof getDisabledState != 'undefined') 部分,它在模板中不太好。
那么,是否还有其他方法可以使用辅助函数来准备模板?
【问题讨论】:
-
我认为你可以在 MarionetteJS 中签出相同的任务实现。模板助手功能非常接近您的任务。
-
Backbone+Marionette+Handlebars 架构怎么样? Handlebars 在
registerHelper中有一个构建,您可以声明您的自定义助手。 -
感谢您的回复,@VahanVardanyan。我确实喜欢 Handlebars,但项目的很大一部分已经在使用 Underscore 模板,现在应该留在里面。
标签: javascript templates backbone.js underscore.js