Created
December 28, 2011 22:53
-
-
Save logicalparadox/1530243 to your computer and use it in GitHub Desktop.
Compile a folder of jade templates for client side use.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var folio = require('folio') | |
, katu = require('katu') | |
, jade = require('jade') | |
, fs = require('fs') | |
, path = require('path'); | |
var paths = [] | |
, basepath = path.join(__dirname, '..', '..', 'src', 'templates') | |
var getFiles = function (p) { | |
fs.readdir(p, function (err, files) { | |
if (err) throw new Error(err); | |
files.forEach(function (filename) { | |
var file = path.join(p, filename); | |
fs.stat(file, function (err, stat) { | |
if (err) throw new Error(err); | |
if (stat.isDirectory()) | |
getFiles(file); | |
else if (stat.isFile()) | |
if (path.extname(file) == '.jade') | |
paths.push(file); | |
}); | |
}); | |
}); | |
}; | |
paths.push(require.resolve('jade/runtime.js')) | |
getFiles(basepath); | |
var templateJs = new folio.glossary(paths, { | |
compilers: { | |
jade: function (name, source, filename) { | |
var title = filename.replace(basepath + '/', '').replace('.jade', ''); | |
return 'template[\'' + title + '\'] = ' + | |
jade.compile(source, { | |
client: true, | |
compileDebug: false | |
}) + ';'; | |
} | |
} | |
}); | |
module.exports = katu({ | |
routes: { | |
'/js/templates.js': 'templates' | |
} | |
, templates: function (req, res) { | |
var prefix = [ | |
"(function (context) {" | |
, "var template = {};" ].join('\n') | |
, suffix = [ | |
"if ( typeof define === 'function' && define.amd ) {" | |
, "define( function () { return template; } );" | |
, "} else {" | |
, "context.templates = template;" | |
, "}" | |
, "})(this);" ].join('\n'); | |
templateJs.compile(function (err, src) { | |
var content = prefix + src + suffix; | |
res.setHeader('Content-Type', 'text/javascript'); | |
res.setHeader('Cache-Control', 'max-age=' + (templateJs.cache || 0)); | |
res.write(content); | |
res.end(); | |
}); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment