【发布时间】:2012-09-20 10:32:46
【问题描述】:
在这个 Backbone 应用程序 http://arturadib.com/hello-backbonejs/docs/5.html 的“hello world”示例中,作者像这样内联呈现模板
render: function(){
$(this.el).html('<span style="color:black;">'+this.model.get('part1')+' '+this.model.get('part2')+'</span> <span class="swap" style="font-family:sans-serif; color:blue; cursor:pointer;">[swap]</span> <span class="delete" style="cursor:pointer; color:red; font-family:sans-serif;">[delete]</span>');
return this; // for chainable calls, like .render().el
},
虽然功能强大,但有点难以管理的 html 连接。
我见过其他 Backbone 应用程序的作者使用下划线的模板功能在视图中设置模板
template: _.template($('#my-template').html()),
然后渲染它而不是html
$(this.el).html(this.template(this.model.toJSON()));
我想在 hello world 应用程序中尝试这种技术,但是当我创建模板文件时,我遇到了它不是严格意义上的 html 的问题。你会注意到它调用函数
this.model.get('part2')
我用作模型的模板(来自另一位作者的应用程序,见下文)仅包含 html。
问题,我需要做什么才能在同一个模板文件中包含 javascript 和 html 以便调用模型?
<script type="text/template" id="item-template">
<div class="company">
<div class="display">
<span class="company-text"></span>
<span class="company-mood">
<span class="mood"></span>
</span>
<span class="company-destroy"></span>
</div>
<div class="edit">
<input class="company-input" type="text" value="" />
</div>
</div>
</script>
【问题讨论】:
-
你是说这些?
<% // arbitrary javascript here %> -
@orangewarp 在 OP 中显示的示例模板中,我可以在 中包含任意 javascript 吗?这是开箱即用的骨干吗?
-
它是 Underscore 的一部分,是 Backbone 的依赖项,所以如果你使用 Backbone,你可以很好地使用 Underscore 的模板系统。哎呀, _.template() 函数是一个下划线函数。 :-) 我在答案中包含了一个链接,可以帮助您弄清楚它是如何工作的。
标签: backbone.js