在Phonegap/Cordova应用中使用Backbone加载HTML本地模板文件

Load HTML local template files with Backbone in a Phonegap/Cordova application

本文关键字:HTML 加载 文件 Backbone Phonegap Cordova 应用      更新时间:2023-09-26

我有这段代码,我想从视图文件夹内的外部文件加载我的HTML模板。

var InputView = Backbone.View.extend({
  tagName: 'form',
  template: _.template($.get('views/inputCapo.html')),
  render: function(){
    app.$el.append(this.template);
    return this;
  }
});

app是我的应用程序的主要视图,我知道本地文件的XHR请求的问题,出于安全原因,我无法加载它。

我知道这是浏览器的问题,但与phonegap应用程序的问题是一样的?

要实现将HTML文件与脚本分开的相同功能,哪个是最佳替代方案?

我已经看到require.jstext.js库加载HTML文件没有$.get,但又有相同的依赖于XHR限制。

预编译模板比动态请求模板性能更高。一种方法是使用Grunt将它们构建到JST命名空间中- https://github.com/gruntjs/grunt-contrib-jst.

然后在你的Gruntfile中,像这样:

jst: {
  compile: {
    files: {
      "path/to/compiled/templates.js": ["path/to/source/**/*.html"]
    }
  }
}

在你的主干视图:

var InputView = Backbone.View.extend({
  tagName: 'form',
  template: JST['views/inputCapo'],
  render: function(){
    app.$el.append(this.template());
    return this;
  }
});

然后确保在您的Backbone视图之前在index.html文件中包含path/to/compiled/templates.js脚本。