Backbone.js and Handlebars – Using grunt-contrib-handlebars-Collection of common programming errors

I’m just wondering if anyone has had experience using this plugin in a backbone project.

Instead of having all my script template tags in a single index file, I wanted to house my templates in the same directory as my views that required them.

So I was hoping i could use the node option to require the local template and render to it and then append to an #id on my index file (which I’ll sort out laster).

So basically I have my handlebars template (template.hbs) and its compiled js (template.js) alongside my backbone view, index.coffee.

public
   |_ coffee
      |_views
        |_card
           |_list
              index.coffee
              template.hbs
              template.js

Just as a reference, my grunt file looks like this:

handlebars: {
      compile: {
        options: {
          namespace: 'MyApp.Templates',
          node: true
        },
        files: {
          "public/coffee/views/card/list/template.js": "public/coffee/views/card/list/template.hbs"
        }
      }
    },

In my backbone view (index.coffee) I was hoping to require the handlebars template like so:

class CardList extends Backbone.View
    template: require('./template')


    . 
    do some other shiz
    .


render: =>
    template = Handlebars.compile($(this.template).html())
    html = template
        model: this.model
    $(this.el).html(html)

Rendering this is spitting out this error in the inspector:

Uncaught [object Object]

> template = handlebars.compile($(this.template).html());

I obviously dont know what I’m doing, so I’m hoping someone could shed some light on how I can use this plugin properly.

I’m using grunt-contrib-handlebars v0.3.5

Any help is appreciated.

Thanks

  1. Look inside your template.js file that you’re including. grunt-comtrib-handlbars should have precompiled it into a Javascript function for you, so there’s no need to call Handlebars.compile anymore. You could just remove that template = Handlebars.compile line.

  2. You might be able to achieve that by building the files object dynamically.

    Maybe something like this, although I’m not sure if cwd supports globbing patterns. I’m also not sure if dest is relative to cwd. If this is not the case, this will not work, but it’s worth a shot.

    handlebars: {
      dist: {
        options: {
          namespace: 'MyApp.Templates',
          node: true
        },
        // Glob for a directory of files, builds the files object, then map each
        // one to a new destination file.
        expand: true,
        cwd: './public/coffee/views/*',
        src: '**/*.hbs',
        dest: './',
        ext: '.js'
      }
    },