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

时间:2014-07-07 17:46:01

标签: javascript jquery html cordova backbone.js

我有这段代码,我想从视图文件夹中的外部文件加载我的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库,用于加载没有$.get的HTML文件,但是对XHR限制的依赖性也是如此。

1 个答案:

答案 0 :(得分:0)

预编译模板可能更加高效,而不是动态请求它们。一种方法是使用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脚本。

相关问题