在骨干js中通过URL加载模板

时间:2013-12-22 14:00:10

标签: javascript ajax backbone.js

我在骨干网中创建了一个View来渲染一个集合。它使用模板格式化数据,模板HTML用字符串变量编写。现在模板变得越来越复杂,我需要将它存储在一个单独的文件中。在骨干网中是否有任何方法可以从URL加载模板,在这种情况下,最佳设计模式是什么。以下是代码:

var PageView = Backbone.View.extend({
    template: _.template("<% _.each(items,function (item) { %><tr><td><%= item.page_id %></td><td><%= item.title %></td></tr><% }); %>"),

    initialize: function () {
        _.bindAll(this, 'render');
        this.model.bind('all', this.render);
    },

    render: function () {
        this.$el.html(this.template({
            items: this.model.toJSON()
        }));
    }

});

是否有类似 templateURL 的内容,以便可以从服务器上的其他文件动态加载。

3 个答案:

答案 0 :(得分:3)

Backbone本身并没有提供这样做的方法,但是有很多不同的方法可以实现这一点,并且有很多关于如何设置所需机制的例子。

如果您选择使用RequireJs(我建议您最终这样做...考虑到您需要一些时间来学习它),您还需要RequireJS的文本插件。有一个在backbone tutorials可用的骨干项目中使用RequireJS和文本插件的教程。

设置项目后,在骨干视图中加载外部模板就像将它们定义为视图的依赖项并将该依赖项传递给变量一样简单(在以下示例中为projectListTemplate):

define([
  'jquery',
  'underscore',
  'backbone',
  // Using the Require.js text! plugin, we load raw text
  // which will be used as our views primary template
  'text!templates/project/list.html'
], function($, _, Backbone, projectListTemplate){
  var ProjectListView = Backbone.View.extend({
    el: $('#container'),
    render: function(){
      // Using Underscore we can compile our template with data
      var data = {};
      var compiledTemplate = _.template( projectListTemplate, data );
      // Append our compiled template to this Views "el"
      this.$el.append( compiledTemplate );
    }
  });
  // Our module now returns our view
  return ProjectListView;
});

另一种可能的方法是,如果您不准备使用RequireJS,并且希望立即将模板移动到不同的文件,则可以使用简单的自定义模板加载器。 Christophe Coenraets编写了自己的作品并将其用于示例骨干项目中。他在github上提供了所有源代码,他还提供了教程和解释。

他在第一部分“外化模板”中写了他的method for externalizing templates

答案 1 :(得分:0)

我会为此使用require.js,它可能在开始时感觉有点矫枉过正,但最终它会带来丰厚的回报。

http://requirejs.org/

答案 2 :(得分:0)

ReuireJS是一条很好的路线,但有点矫枉过正,并补充说我们在其上使用了requireJS插件这一事实 - 我决定不使用它。 我的解决方案是在加载View之前使用JQuery $ .get模板HTML,然后在结果中加载构造函数中定义模板的View,然后调用options.template:

var template = $.get("/templates/needed_template.html")
                        .done(function (res) {
                            ns.myView = new MyView({template: res});
                            ns.myView.render();
                        })

在View方面,我添加了这个:

initialize: function() {
   this.template = _.template(this.options.template);