abbett.org

i.e. Jonathan Abbett — web crafter, healthcare designer, amateur kosher cheesemaker.

Loading Handlebars templates via AJAX

12 December 2012
My tweaks to Tal Bereznitskey's method for dynamically loading & compiling Handlebars templates

I implemented Tal Bereznitskey's method for dynamically loading & compiling Handlebars templates with a jQuery $.ajax call, and all was well, until I checked out my code on a new computer, and saw this error in the Chrome console:

Uncaught TypeError: Object #<Document> has no method 'match' 

It appeared whenever I tried to render my template, e.g.

var tpl = Handlebars.getTemplate('login');
$(this.el).html(tpl());

Fortunately, after a couple hours of struggling, I discovered this post on Stack Overflow, and started using jqXHR.responseText as the input to Handlebars.compile() - problem solved.

Handlebars.getTemplate = function(name) {
    if (Handlebars.templates === undefined || Handlebars.templates[name] === undefined) {
        $.ajax({
            url : 'js/templates/' + name + '.handlebars',
            datatype: 'text/javascript',
            success : function(response, status, jqXHR) {
                if (Handlebars.templates === undefined) {
                    Handlebars.templates = {};
                }
                //Handlebars.templates[name] = Handlebars.compile(jqXHR.responseText);
                Handlebars.templates[name] = Handlebars.compile(response);
            },
            async : false
        });
    }
    return Handlebars.templates[name];
};
comments powered by Disqus
Uncaught Exception

Uncaught Exception

Function get_magic_quotes_gpc() is deprecated

Origin

system/boot.php on line 41

Trace

#0 [internal function]: System\Error::shutdown()
#1 {main}