テンプレートは、アンダースコアが関係する限り文字列であり、その文字列をどこからでも取得できます。これを行うことができます:
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>
秒のうち、テンプレートを引く:
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;
}
});