External handlebars templates backbone marionette

こ雲淡風輕ζ 提交于 2019-12-23 15:42:15

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/11054239/external-handlebars-templates-backbone-marionette

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!