Search code examples
backbone.jsrequirejshandlebars.jsyeomanyeoman-generator

JST is undefined - Yeoman , Backbone - Template cannot be loaded


Am new to Yeoman and I generated a Backbone application using generator-backbone

This is my main.js ( require js config)

/*global require*/
'use strict';
require.config({
    shim: {,
        handlebars: {
            exports: 'Handlebars'
        }
    },
    paths: {
        jquery: '../bower_components/jquery/dist/jquery',
        backbone: '../bower_components/backbone/backbone',
        underscore: '../bower_components/lodash/dist/lodash',
        handlebars: '../bower_components/handlebars/handlebars'
    }
});

require([
    'backbone'
], function (Backbone) {
    Backbone.history.start();
});

Now I created a view using yo backbone:view Login

This is the generated view

define([
    'jquery',
    'underscore',
    'backbone',
    'templates'
], function ($, _, Backbone, JST) {
    'use strict';

    var LoginViewView = Backbone.View.extend({
        template: JST['app/scripts/templates/LoginView.hbs'],

        tagName: 'div',

        id: '',

        className: '',

        events: {},

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

        render: function () {
            this.$el.html(this.template(this.model.toJSON()));
        }
    });

    return LoginView;
});

When I run the app with LoginView, i get an error

Error: Script error for: templates http://requirejs.org/docs/errors.html#scripterror

Apparently I see templates is no where defined in main.js. What am i missing while running the yeoman generator


Solution

  • If you did the same blunder mistake like m, just verify this

    After generating the code, and if its shows template is undefined or u find the template.js missing, check the following steps

    1. run grunt handlebars (include --force if you want to ignore any warning/errors)
    2. This will pre compile the .hbs file make a single template.js file.

    But the catch here is, it wont work out of the box, the template.js is written in the location app/.tmp/scripts/template.js location.

    You can modify main require configure file accordingly, or open GruntFile.js and modify this function

    grunt.registerTask('createDefaultTemplate', function () {
            grunt.file.write('/your/custom/path/to/templates.js', 'this.JST = this.JST || {};');
        });
    

    Also verify if u have this line in GruntFile.js

    grunt.loadNpmTasks('grunt-contrib-handlebars');
    

    if not, add it at the very last (ofcourse not after the function block)