Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define Handlebar.js templates in an external file

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?

like image 478
Naveen Avatar asked Apr 11 '14 13:04

Naveen


People also ask

How do I compile handlebars templates?

Getting started Next, install the Handlebars npm package, which contains the precompiler. Create a file name example. handlebars containing your template: Handlebars <b>{{doesWhat}}</b> precompiled!

What should be the extension for the separate template file in handlebars?

hbs is one of the appropriate extension for handlebars templates, as seen here : github.com/github/linguist/blob/master/lib/linguist/…

Is handlebars a template engine?

Handlebars: What it is and Why to Use itHandlebars is a logic-less templating engine that dynamically generates your HTML page.


2 Answers

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).

like image 194
Jeremy Belolo Avatar answered Sep 16 '22 20:09

Jeremy Belolo


You can use AJX to load them.

Here's an example function which accepts a URL to a Handlebars template, and a callback function. The function loads the template, and calls the callback function with the compiled Handlebars template as a parameter:

function loadHandlebarsTemplate(url, callback) {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4 && xhr.status == 200) {
            var raw = xhr.responseText;
            var compiled = Handlebars.compile(raw);
            callback(compiled);
        }
    };
    xhr.send();     
}

For example, assume you have a Handlebars template defined in a file named /templates/MyTemplate.html, such as:

<p>The current date is {{date}}</p>

You can then load that file, compile it and render it to the UI, like this:

var url = '/templates/MyTemplate.html';
loadHandlebarsTemplate(url, function(template) {
    $('#container').html(template({date: new Date()}));
});

An even better solution, would be to pre-compile the templates which would speed up the time they take to load. More info on precompilation can be found here.

like image 23
Gwyn Howell Avatar answered Sep 19 '22 20:09

Gwyn Howell