Skip to content

Instantly share code, notes, and snippets.

@engram-design
Last active December 17, 2015 02:58
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save engram-design/5539338 to your computer and use it in GitHub Desktop.
Save engram-design/5539338 to your computer and use it in GitHub Desktop.
A demonstration of using Handlebars with Backbone.Marionette. Utilizes Grunt.js task (grunt-contrib-handlebars) to pre-compile templates, and swaps Handlebars.runtime for further optimization. Feel free to comment if you have any suggestions or questions!
define([
'marionette',
'templates'
], function(Marionette, Templates) {
var app = new Marionette.Application({
root: '/',
templates: Templates
});
return app;
});
require.config({
deps: ['main'],
paths: {
jquery: '../vendor/js/libs/jquery',
underscore: '../vendor/js/libs/lodash.underscore',
backbone: '../vendor/js/libs/backbone',
handlebars: '../vendor/js/libs/handlebars',
marionette: '../vendor/js/libs/backbone.marionette',
text: '../vendor/js/libs/text',
hbars: '../vendor/js/libs/hbars'
},
shim: {
handlebars: { exports: 'Handlebars' },
marionette: {
deps: ['jquery', 'underscore', 'backbone'],
exports: 'Marionette'
}
}
});
module.exports = function(grunt) {
grunt.initConfig({
handlebars: {
"dist/debug/templates.js": ["app/templates/**/*.html"]
},
requirejs: {
mainConfigFile: "app/config.js",
out: "dist/debug/require.js",
name: "config",
wrap: false,
paths: {
handlebars: "../vendor/js/libs/handlebars.runtime"
}
}
});
grunt.registerTask("debug", "handlebars requirejs");
};
define(['handlebars'], function(Handlebars) {
var buildMap = {};
return {
load: function (name, parentRequire, onload, config) {
if (config.isBuild) {
var fsPath = config.dirBaseUrl + '/' + name + '.html'; // TODO - add ext into config options
buildMap[name] = nodeRequire('fs').readFileSync(fsPath).toString();
onload();
}
else {
var JST = window.JST ? window.JST : {};
var path = 'app/' + name + '.html'; // TODO: add path into config options
if (JST[path]) {
// Grunt.js pre-compiles templates into JST[]
onload(Handlebars.template(JST[template]));
} else {
// use text.js plugin when loading templates during development
parentRequire(['text!' + name + '.html'], function(raw) {
onload(Handlebars.compile(raw));
});
}
}
}
};
});
define([
'app'
], function(app) {
var Module = app.module('Module');
Module.Views = {};
Module.Views.Index = Backbone.Marionette.ItemView.extend({
template: app.templates.ModuleTemplate
});
return Module;
});
define(function(require){
return {
// Layout/Region templates
AppLayout: require('hbars!templates/layout_app'),
ModuleTemplate: require('hbars!templates/module_template')
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment