2012-04-10 128 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 

不要忘了運行包&重啓服務器