Underscore に関する限り、テンプレートは単なる文字列であるため、その文字列はどこからでも取得できます。だからあなたはこれを行うことができます:
render: function() {
var that = this;
$.get('/some_template', function(tmpl) {
that.$el.html(_.template(tmpl, that.model.toJSON()));
});
return this;
}
実際には、サーバーから特定のテンプレートを 1 回だけ取得する単純なキャッシュ オブジェクトの背後にそれを隠したいと思うでしょう。
または、サーバー コードに必要なテンプレートのセットを判断させ、それらを<script>
要素に埋め込むことができます。
<script id="tmpl1" type="text/template">
Some template code...
</script>
<script id="tmpl2" type="text/template">
Some template code...
</script>
...
<script>
テンプレートをsから引き出します。
render: function() {
var tmpl = _.template($('#tmpl1').html());
this.$el.html(tmpl(this.model.toJSON()));
return this;
}
また、コンパイルされたテンプレート をtmpl
どこかにキャッシュするか、ビュー クラスを定義するときにコンパイルすることもできます (もちろん、DOM の準備が十分に整っていると仮定します)。
var V = Backbone.View.extend({
template: _.template($('#tmpl1').html()),
//...
render: function() {
this.$el.html(this.template(this.model.toJSON()));
return this;
}
});