2012-04-10 121 views
1

我有一个Rails 3.2.3项目的Backbone.js,它可以工作,但我想清理它并将模板放入单独的JST文件中。Rails 3.2中的Backbone.js模板文件

我首先创建一个目录来保存我的模板

<project>/app/assets/templates/appointments 

然后我在那里叫“show.jst”创建的文件。

从我读过,我不需要在Rails的3.2.x中安装Jammit所以我就跟着去了,并试图转换下面的代码使用外部模板文件:

window.AppointmentView = Backbone.View.extend({ 
    template: _.template('<h3><%= topic %></h3>'), 

    render: function(){ 
     var attributes = this.model.toJSON(); 
     this.$el.html(this.template(attributes)); 
     return this; 
    } 
}); 

这里我试图至今:

window.AppointmentView = Backbone.View.extend({ 
    render: function(){ 
     var attributes = this.model.toJSON(); 
     var html = JST['appointments/show'](attributes); 
     this.$el.html(html); 
     return this; 
    } 
}); 

里面我show.jst文件我有以下几点:

<h3><%= topic %></h3> 

(主题是我的'约会'模型中的一个字段)

这不会在屏幕上显示任何错误,也不会在屏幕上显示任何内容。

如何解决这个问题,以便我可以使用外部模板文件?

更新

我确信我有所有其他需要像这样的语句之前required_tree ./templates或../templates(根据我测试出的位置):

#= require jquery 
#= require jquery_ujs 
#= require backbone-rails 
#= require_tree ../templates 
#= require_tree ./models 
#= require_tree ./collections 
#= require_tree ./views 
#= require_tree ./routers 

我试图把我的show.jst模板文件在以下

应用程序/资产/ Java脚本/模板/约会/ show.jst

app/assets/templates/appointmentments/show.jst

我已经尝试命名文件show.jst.ejs并在gemfile中包含gem'ejs'。

这些都没有加载模板。当存储在应用我的模板/资产我确信这是我与以下路径:

config.assets.paths << "#{ Rails.root }/app/assets/templates" 

这并没有帮助,但它没有摆脱链轮错误的。

我还没有能够加载模板jst文件,我读的所有东西都提供了不同的方式。我已经尝试了很多这些,可能它们与Rails 3.2.3不兼容。

回答

3

我发现这个效果很好。在我appointment_show.js我打电话给我的模板,像这样:

window.AppointmentView = Backbone.View.extend({ 
    template: JST["appointments/show"], 

    render: function(){ 
     this.$el.html(this.template(this.model.toJSON())); 
     return this; 
    } 
}); 

我要确保我包括在我的应用程序模板目录。JS:

#= require jquery 
#= require jquery_ujs 
#= require backbone-rails 
#= require_tree ../templates 
#= require_tree ./models 
#= require_tree ./collections 
#= require_tree ./views 
#= require_tree ./routers 

在你的Gemfile

gem 'backbone-rails' 
gem 'ejs' 

包括这些宝石的应用程序/资产/模板目录添加到您的environment.rb路径中:

AppointmentsBackboneJs::Application.configure do 
    config.assets.paths << "#{ Rails.root }/app/assets/templates" 
end 

不要忘了运行包&重启服务器