//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');
此代码有效!为什么我们必须先追加我不知道...
答案 0 :(得分:0)
你可能遇到了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并将内容从该脚本块中拉出来来完成我认为您要完成的任务。