每当我在Backbone视图中添加template: JST["users/show"]时,都会出现以下两个错误:
Uncaught ReferenceError: JST is not defined
Uncaught TypeError: Twitter.Views.UserShow is not a function

我查看了关于JST的所有问题,这些问题未在stackoverflow上定义,但我无法弄清楚该问题。我也跑了rails g backbone:install

这是我的档案

application.js

//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require underscore
//= require backbone
//= require twitter
//= require_tree ../templates
//= require_tree ./models
//= require_tree ./collections
//= require_tree ./views
//= require_tree ./routers
//= require_tree .


router.js

Twitter.Routers.Router = Backbone.Router.extend({

  initialize: function (options) {
    this.$rootEl = options.$rootEl;
    this.users = new Twitter.Collections.Users ();
  },

  routes: {
    'users/:id': 'userShow'
  },

  userShow: function(id) {
    var user = this.users.getOrFetch(id);
    var showView = new Twitter.Views.UserShow ({
      model: user
    });

    this.$rootEl.html(showView.render().$el);
  }

});


user.js

Twitter.Collections.Users = Backbone.Collection.extend ({

  url: '/api/users',
  model: Twitter.Models.User,

  getOrFetch: function (id) {
    var user = this.get(id);
    var users = this;
    if (user) {
      user.fetch();
    } else {
      user = new Twitter.Models.User ( {id: id });
      user.fetch({
        success: function () {
          users.add(user)
        }
      });
    }

    return user;
  }

});


user.js

Twitter.Models.User = Backbone.Model.extend ({

  urlRoot: '/api/users'

});


show.js

Twitter.Views.UserShow = Backbone.View.extend ({

  template: JST["users/show"],

  initialize: function () {
    this.listenTo(this.model, 'sync', this.render);
  },

  render: function () {
    // console.log(this.model.get("username"))
    var content = this.template({ user: this.model });
    this.$el.html(content);

    return this;
  }

});


show.jst.ejs(在模板/用户内部)

<%= user.escape("username") %>

console.log(this.model.get("username")返回正确的用户名。

最佳答案

我必须在其中添加config.assets.paths << "app/assets/templates"

module TwitterClone
  class Application < Rails::Application

    config.active_record.raise_in_transactional_callbacks = true
    config.assets.paths << "app/assets/templates"
  end
end

09-08 11:12