2014-01-21 94 views
0
//path = the location of the external file 
//scriptBlockId = the id of the external script block (<script id="add-form-tempate" type="text/html-template">) 
//fillId = where you want to place the template when rendered 
var App = Backbone.View.extend({ 
render: function (path, scriptBlockId, fillId) { 

    $.ajax({ 
     async: false, 
     dataType: 'html', 
     method: 'GET', 
     url: path, 
     success: function (response) { 
      //Not sure why we have to do this first, before we can select the script block? 
      var section = $('#main').append(response); 

      var templateString = $(section).find('#' + scriptBlockId).html(); 
      var compiledTemplate = _.template(templateString); 
      var temp = compiledTemplate(); 

      $(fillId).html(temp); 
     } 
    }); 

} 
}); 

var app = new App(); 
app.render(window.siteRoot + 'Scripts/_test1.tmpl.html', 'add-form-template', '#main'); 

此代碼有效!爲什麼我們必須先追加我不知道的......使用Underscore.js加載外部模板

+0

通知異步:假 – Mark

回答

0

您可能有問題w/aysnc $.ajax

var App = Backbone.View.extend({ 
    render: function(path, scriptBlockId, fillId) { 
     var self = this; 

     $.ajax({ 
      async: false, 
      dataType: 'html', 
      method: 'GET', 
      url: path, 
      success: function(response) { 
       var templateString = $(response).find(scriptBlockId)[0].innerHTML, 
        compildeTemplate = _.template(templateString), 
        temp = compildeTemplate(); 

       $(fillId).html(temp); 
      } 
     }); 

     return this; 
    } 
}); 

var app = new App(); 
app.render(window.siteRoot + 'Scripts/_test1.tmpl.html', 'add-form-tempate', '#main'); 

我也試圖做什麼,我想你想通過搜索HTML結果的ID和拉內容指出,腳本塊來完成。

+0

這看起來很接近但引發錯誤:TypeError:$(...)。find(...)[0]是undefined – Mark

+0

對於我的生活,我不明白爲什麼這不起作用?它可以帶回外部文件很好,但我不能得到代碼塊! – Mark

+0

@Mark可能首先將它追加到'body'? – asawyer