How to define Handlebar.js templates in an external file

Naveen picture Naveen · Apr 11, 2014 · Viewed 10k times · Source

I am currently defining my Handlebars templates within the same HTML file in which they will be used.

Is it possible to define them as external templates, which can be called when the page is loaded?

Answer

Jeremy Belolo picture Jeremy Belolo · Aug 2, 2015

For those that get here through Google search like I did, I finally found the perfect answer in this post, check it out :

http://berzniz.com/post/24743062344/handling-handlebarsjs-like-a-pro

Basically you need to implement a method, getTemplate :

Handlebars.getTemplate = function(name) {
    if (Handlebars.templates === undefined || Handlebars.templates[name] === undefined) {
        $.ajax({
            url : 'templatesfolder/' + name + '.handlebars',
            success : function(data) {
                if (Handlebars.templates === undefined) {
                    Handlebars.templates = {};
                }
                Handlebars.templates[name] = Handlebars.compile(data);
            },
            async : false
        });
    }
    return Handlebars.templates[name];
};

and then call your template with it :

var compiledTemplate = Handlebars.getTemplate('hello');
var html = compiledTemplate({ name : 'World' });

That way, if you precompiled the templates (great for production use) it will find it directly, otherwise it will fetch the template and compile it in the browser (that's how you work in development).