Skip to content

Instantly share code, notes, and snippets.

@msaglietto
Created September 26, 2012 22:05
Show Gist options
  • Save msaglietto/3790923 to your computer and use it in GitHub Desktop.
Save msaglietto/3790923 to your computer and use it in GitHub Desktop.
var fs = require('fs'),
readCache = {},
Y = require('yui/handlebars'),
templates = require('./templates'),
partials = templates.getRaw();
function read(path, options, fn) {
var str = readCache[path];
// cached (only if cached is a string and not a compiled template function)
if (options.cache && str && typeof str === 'string') return fn(null, str);
// read
fs.readFile(path, 'utf8', function(err, str) {
if (err) return fn(err);
if (options.cache) readCache[path] = str;
fn(null, str);
});
}
// Export a function to work as Template Engine of Express
module.exports = function(path, options, fn) {
read(path, options, function(err, str) {
if (err) {
return fn(err);
}
try {
var template = Y.Handlebars.compile(str),
parsed = template(options, {
partials: partials
});
if (options.layout) {
read('views/' + options.layout + '.handlebars', options, function(err, str) {
if (err) {
return fn(err);
}
try {
var layoutTemplate = Y.Handlebars.compile(str);
options.body = parsed;
var layoutParsed = layoutTemplate(options, {
partials: partials
});
return fn(null, layoutParsed);
} catch (ex) {
fn(ex);
}
});
} else {
return fn(null, parsed);
}
} catch (ex) {
fn(ex);
}
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment