Precompiled Handlebars templates in Backbone with Requirejs?

浪子不回头ぞ 提交于 2019-12-03 01:51:56

Have a look at the Requirejs-Handlebarsjs plugin: https://github.com/SlexAxton/require-handlebars-plugin

A simple approach is to create a RequireJS plugin based on the existing text! plugin. This will load and compile the template. RequireJs will cache and reuse the compiled template.

the plugin code:

// hbtemplate.js plugin for requirejs / text.js
// it loads and compiles Handlebars templates
define(['handlebars'],
function (Handlebars) {

    var loadResource = function (resourceName, parentRequire, callback, config) {
        parentRequire([("text!" + resourceName)],
            function (templateContent) {
                var template = Handlebars.compile(templateContent);
                callback(template);
            }
        );
    };

    return {
        load: loadResource
    };

});

configuration in main.js:

require.config({
    paths: {
        handlebars: 'libs/handlebars/handlebars',
        hb: 'libs/require/hbtemplate',
    }
});

usage in a backbone.marionette view:

define(['backbone', 'marionette',
        'hb!templates/bronnen/bronnen.filter.html',
        'hb!templates/bronnen/bronnen.layout.html'],
        function (Backbone, Marionette, FilterTemplate, LayoutTemplate) {
        ...

In case you use the great Backbone.Marionette framework you can override the default renderer so that it will bypass the builtin template loader (for loading/compiling/caching):

Marionette.Renderer = {
    render: function (template, data) {
        return template(data);
    }
};
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!