2

我的预编译模板文件是 templates.js——如何使用 RequireJS 加载这个文件?

requirejs.config({
    paths: {
        jquery: '../bower_components/jquery/jquery'
        , underscore: '../bower_components/underscore/underscore'
        , handlebars: '../bower_components/handlebars/handlebars'
        , moment: '../bower_components/momentjs/moment'
        , spin: '../bower_components/spinjs/spin'
        , templates: 'templates'
    },
    shim: {
        handlebars: {
            exports: 'Handlebars'
        },
        templates: {
            deps: ['handlebars']
        }
    }
});

requirejs(["jquery", "underscore", "handlebars", "templates", "moment", "spin", "test"], function($, _, Handlebars, Templates, moment, Spinner, test) {
    test.init();
});
4

1 回答 1

1

您应该在AMD支持下编译您的模板。(我通常在这个 Grunt插件的帮助下完成。)

   requirejs.config({
    paths: {
        jquery: '../bower_components/jquery/jquery'
        , underscore: '../bower_components/underscore/underscore'
        , handlebars: '../bower_components/handlebars/handlebars'
        , moment: '../bower_components/momentjs/moment'
        , spin: '../bower_components/spinjs/spin'
        , templates: 'templates'
    },
    shim: {
        handlebars: {
            exports: 'Handlebars'
        }
    }
});

requirejs(["jquery", "underscore", "templates", "moment", "spin", "test"]
    , function($, _, Templates, moment, Spinner, test) {
        test.init();
});

NowTemplates是一个对象,其键是模板的名称,其值是 Handlebars 模板函数。

用法示例:

var template = Templates['templates/posts.hbs'];
document.body.innerHTML = template({
    title: 'All posts',
    posts: [
        { title: 'First post', '13/11/2013'},
        { title: 'Second post', '15/11/2013'}
    ]    
});
于 2013-12-12T10:51:44.657 回答