camaya
camaya

Reputation: 377

External handlebars templates backbone marionette

In my application i added Marionette.sync plugin and override these methods:

Backbone.Marionette.TemplateCache.prototype.loadTemplate = function (templateId, callback) {
    var tmpId = templateId.replace("#", ""),
        url = "/app/templates/" + tmpId + ".html";

    $.get(url, function (templateHtml) {
        compiledTemplate = Handlebars.compile($(templateHtml).html())
        callback.call(this, compiledTemplate);
    });
};

Backbone.Marionette.Renderer.renderTemplate = function (template, data) {
    template(data);
};

But this not work, any ideas?

Upvotes: 4

Views: 2725

Answers (1)

Derick Bailey
Derick Bailey

Reputation: 72878

I assume you're running v0.9 of Marionette since you mention the Marionette.Async plugin.

The Renderer change is slightly off in the method name, and nothing is calling your TemplateCache object anymore.

If you're intending to use pre-compiled Handlebars functions, then you only need to do this:


Backbone.Marionette.Renderer.render = function(template, data){
  return template(data);
};

If you intend to have the template loaded asynchronously and then compiled, using the TemplateLoader, your code would need to look like this:


Backbone.Marionette.TemplateCache.prototype.loadTemplate = function (templateId, callback) {
    var tmpId = templateId.replace("#", ""),
        url = "/app/templates/" + tmpId + ".html";

    $.get(url, function (templateHtml) {
        compiledTemplate = Handlebars.compile($(templateHtml).html())
        callback.call(this, compiledTemplate);
    });
};

Backbone.Marionette.Renderer.renderTemplate = function (templateId, data) {
    var renderer = $.Deferred();
    Backbone.Marionette.TemplateCache.get(templateId, function(template){
      var html = template(data);
      renderer.resolve(html);
    });
    return renderer.promise();
};

The Renderer is responsible for calling the TemplateCache.


Side note: what article / blog post / wiki page / documentation were you using to get your code from? I have probably missed some pages that need to be updated.

Upvotes: 7

Related Questions