我们目前在我们的应用程序中使用underscore.js
个模板;我们有几个辅助函数可以为我们处理一些重复的操作。
有没有办法将整个当前范围传递给辅助函数?
答案 0 :(得分:1)
如果你正在使用Marionette,你可能想要利用templateHelpers
。在您看来:
var view = Backbone.Marionette.ItemView.extend({
template: "#my-template",
templateHelpers: {
model: function() {
return this; // `this` will be the model passed in to the view
}
}
});
// Or, define as object rather than helper function
var view2 = Backbone.Marionette.ItemView.extend({
template: "#my-template",
templateHelpers: function () {
return {
model: this
}
}
});
在你的模板中:
<% model().propertyName %>
<!-- Using the alternate format -->
<% model.propertyName %>
如果您只是使用没有Marionette的下划线模板系统,如评论中所述,您只需要将模型作为键而不是模型传递对象:
model = {'propertyName': 'someValue'};
template = _.template('<% model.propertyName %>');
// Instead of `template(model)`
template({'model': model});
答案 1 :(得分:1)
有点迟了......关于木偶
,但只需要做这样的事情并在模板中使用参数[0]发送整个模型,绑定到模板到另一个函数:
<script type="text/html" id="someTemplate">
...render some stuff
<%= getMoreHtml(arguments[0]) %>
</script>
then
getMoreHtml(model) {
//return some html where model is the serialized model passed to the prev template
}
这是有效的,因为模型被传递给Marionette.Renderer.render方法,在其内部,数据作为唯一参数传递给templateFunc