0

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?

Community
  • 1
  • 1
timhc22
  • 7,213
  • 8
  • 48
  • 66
  • I'll give that a try, but what would (whatever_data) be though? because it is just an html file with some html in it – timhc22 Apr 18 '15 at 23:04

1 Answers1

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.

Levsero
  • 591
  • 1
  • 4
  • 14
  • I have given this a go, but get a strange '_ is not defined error'. Wonder if it is trying to use Underscore.js. It is on this line anyway: `var __t, __p = '', __e = _.escape;` – timhc22 Apr 20 '15 at 11:08
  • ah interesting, it is underscore, I added it to the page using cdn (instead of browserify) and it is working now! I'll need to figure out a way of organising this with browserify now: either 'requiring' template.js, or somehow injecting underscore into JST – timhc22 Apr 20 '15 at 11:13
  • got it! a little bit hacky maybe, but because I'm using browserify and require, I used gulp to add a require underscore line to the top of the JST file (can't seem to assign a variable to this file and inject it in in another way). – timhc22 Apr 20 '15 at 11:47