1

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 / asset / javascripts /テンプレート/appointments/show.jst

app / asset /テンプレート/appointments/show.jst

ファイルshow.jst.ejsに名前を付けて、Gemファイルにgem'ejs'を含めてみました。

これらのどれもテンプレートをロードしませんでした。テンプレートをアプリ/アセットの下に保存するとき、次のようにテンプレートが自分のパスにあることを確認しました。

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

これも役に立ちませんでしたが、Sprocketsエラーを取り除きました。

私はまだテンプレートjs​​tファイルをロードすることができませんでした、そして私が読んだすべては別の方法を示唆しています。私はこれらの多くを試しましたが、おそらくRails3.2.3とはまだ互換性がありません。

4

1 に答える 1

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;
    }
});

application.jsにtemplatesディレクトリが含まれていることを確認します。

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

これらのgemをGemfileに含めます

gem 'backbone-rails'
gem 'ejs'

app / Assets/templatesディレクトリをenvironment.rb内のパスに追加します。

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

バンドルを実行してサーバーを再起動することを忘れないでください

于 2012-04-11T01:43:38.250 に答える