使用jQuery.load在另一个模板中显示模板

时间:2017-02-13 10:22:15

标签: javascript backbone.js underscore.js-templating

我得到 2个模板:一个用于表单,另一个用于用于结果。这就是我的观点。表单正在显示,但是当我有时,我只获得此行的静态模板,我的意思是<% = key %>不起作用且表单消失。

APP.FromFront = Backbone.View.extend({
    el: $("#content"),
    events: {
        "click #addLink" : "addLink",
        "click .deleteLink" : "deleteLink"
    },
    template: _.template($('#content').html()),

    initialize: function() {
        this.bookmarks = new APP.BookmarksCollection();
        this.render();
    },
    render: function() {
        this.$el.html( this.$el.load( "../../templates/form_template.html" ));
        this.bookmarks.each(function(bookmark) {
            var bookJSON = bookmark.toJSON();
            **//############ this is where it's doesn't work**
            var temp=_.template(this.$el.load( "../../templates/links_template.html" )); 
            $("#links").append(temp(bookJSON));
        },this);
    },
})

1 个答案:

答案 0 :(得分:2)

load是异步的。你需要这样处理它。此外,您应该在加载模板后缓存模板,而不是尝试重复获取相同的模板。尝试以下内容:

APP.FromFront = Backbone.View.extend({
  el: $("#content"),
  events: {
    "click #addLink": "addLink",
    "click .deleteLink": "deleteLink"
  },
  initialize: function() {
    this.bookmarks = new APP.BookmarksCollection();
    this.formTemplatePromise = $.get("../../templates/form_template.html");
    this.linkTemplatePromise = $.get("../../templates/links_template.html");
    $.when(this.formTemplatePromise, this.linkTemplatePromise)
     .then(function(formTemplate, linkTemplate) {
        this.formTemplate = _.template(formTemplate);
        this.linkTemplate = _.template(linkTemplate);
        this.render();
     }.bind(this));
  },
  render: function() {
    this.$el.html(this.formTemplate( /* form data here? */ ));
    var links = [];
    this.bookmarks.each(function(bookmark) {
      // below code can be made a 1 liner, I split it for readability
      var bookJSON = bookmark.toJSON();
      var link = this.linkTemplate(bookJSON);
      links.push(link);
    }, this);
    // Single append instead of many for performance
    $("#links").append(links);
  }
});