【问题标题】:Backbone.js template files in Rails 3.2Rails 3.2 中的 Backbone.js 模板文件
【发布时间】:2012-04-10 05:10:11
【问题描述】:

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

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

<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>

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

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

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

更新

在所有其他 require 语句之前,我已确保我有 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 模板文件放在下面

app/assets/javascripts/templates/appointments/show.jst

app/assets/templates/appointments/show.jst

我尝试将文件命名为 show.jst.ejs 并在我的 Gemfile 中包含 gem 'ejs'。

这些都没有加载模板。将我的模板存储在 app/assets 下时,我确保它在我的路径中,并带有以下内容:

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

这也没有帮助,但它确实消除了 Sprockets 错误。

我仍然无法加载模板 jst 文件,而且我阅读的所有内容都暗示了不同的方式。我已经尝试了很多,可能它们还与 Rails 3.2.3 不兼容。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 backbone.js


    【解决方案1】:

    我发现这很好用。在我的 modify_show.js 中,我这样称呼我的模板:

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

    我确保在我的 application.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'
    

    将 app/assets/templates 目录添加到 environment.rb 中的路径:

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

    别忘了运行 bundle 并重启服务器

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-03
      • 1970-01-01
      相关资源
      最近更新 更多