chovy
chovy

Reputation: 75834

How do I load precompiled Handlebar templates with Require.js?

My precompiled template file is templates.js -- how do I load this file using RequireJS?

requirejs.config({
    paths: {
        jquery: '../bower_components/jquery/jquery'
        , underscore: '../bower_components/underscore/underscore'
        , handlebars: '../bower_components/handlebars/handlebars'
        , moment: '../bower_components/momentjs/moment'
        , spin: '../bower_components/spinjs/spin'
        , templates: 'templates'
    },
    shim: {
        handlebars: {
            exports: 'Handlebars'
        },
        templates: {
            deps: ['handlebars']
        }
    }
});

requirejs(["jquery", "underscore", "handlebars", "templates", "moment", "spin", "test"], function($, _, Handlebars, Templates, moment, Spinner, test) {
    test.init();
});

Upvotes: 2

Views: 681

Answers (1)

Alexander
Alexander

Reputation: 12795

You should compile your templates with AMD support . ( I usually do it with help of this Grunt plugin .)

   requirejs.config({
    paths: {
        jquery: '../bower_components/jquery/jquery'
        , underscore: '../bower_components/underscore/underscore'
        , handlebars: '../bower_components/handlebars/handlebars'
        , moment: '../bower_components/momentjs/moment'
        , spin: '../bower_components/spinjs/spin'
        , templates: 'templates'
    },
    shim: {
        handlebars: {
            exports: 'Handlebars'
        }
    }
});

requirejs(["jquery", "underscore", "templates", "moment", "spin", "test"]
    , function($, _, Templates, moment, Spinner, test) {
        test.init();
});

Now Templates is an object whose keys are the names of the templates and whose values are the Handlebars templating functions .

Usage example :

var template = Templates['templates/posts.hbs'];
document.body.innerHTML = template({
    title: 'All posts',
    posts: [
        { title: 'First post', '13/11/2013'},
        { title: 'Second post', '15/11/2013'}
    ]    
});

Upvotes: 1

Related Questions