问题
I am using Backbone and Underscore to create a small test site.
I am compiling all my html template files into one JST javascript file as suggested here and here.
It isn't however very obvious how to use this with template files. I have tried this:
App.HeaderView = Backbone.View.extend({
el: '#headerContent',
template: JST['header.html'](),
//template: window["JST"]["header.html"],
//template: _.template("<h1>Some text</h1>"),
initialize: function () {
this.render();
},
render: function() {
//var html = this.template();
//// Append the result to the view's element.
//$(this.el).append(html);
this.$el.html(this.template());
return this; // enable chained calls
}
});
The error I get is JST.header.html is not a function.
(The final commented out bit works by the way template: _.template("<h1>Some text</h1>")
so I know the problem isn't with anything else).
It might be because I am using browserify (so have tried 'requiring' the file), but I have tried several different ways of 'including' the template file, including adding it directly:
<script src="templates/_templates.js"></script>
<script src="js/functions.js"></script>
</body>
</html>
Any ideas what needs to be done to get this to work?
回答1:
On line 3 you don't want to invoke the template, rather just use:template: JST['header.html']
.
Currently you're setting template to equal the return value of the function and then trying to invoke that return value instead of the actual function, so it is raising a "is not a function" error.
来源:https://stackoverflow.com/questions/29723392/jst-with-backbone-and-underscore