Skip to content

Instantly share code, notes, and snippets.

@jed jed/node-tmpl.js
Created Nov 4, 2009

Embed
What would you like to do?
a template module for node.js
// tmpl-node.js: a template module for node.js
// Jed Schmidt - http://jedschmidt.com/
//
// inspired by John Resig's micro templates
// http://ejohn.org/blog/javascript-micro-templating/
var posix = require( "posix" ),
concat = Array.prototype.concat;
process.mixin( exports, {
compile: compile,
load: load,
defaultContexts: []
});
function compile( str, name ) {
var fn = new Function( "o",
"var p=[];with(o){p.push('" +
str.replace(/[\r\t\n]/g, " ")
.replace(/'(?=[^%]*%>)/g,"\t")
.split("'").join("\\'")
.split("\t").join("'")
.replace(/<%=(.+?)%>/g, "',$1,'")
.split("<%").join("');")
.split("%>").join("p.push('")
+ "');}return p.join('');"
);
function ret() {
var args = concat.apply( exports.defaultContexts, arguments ),
i = args.length,
context = {},
name,
cur;
if ( i < 2 )
return fn( args[0] || context );
while ( i )
for ( name in ( cur = args[ --i ] ) )
context[ name ] = cur[ name ];
return fn( context );
};
if ( typeof name === "string" )
exports[ name ] = ret;
return ret;
};
function load( dir, pattern ) {
var promise = new process.Promise();
posix.readdir( dir ).addCallback( function( files ) {
var count = files.length;
files.forEach( function( name ) {
if ( pattern && !pattern.test( name ) )
return --count;
posix.cat( dir + name ).addCallback( function( contents ) {
compile( contents, name );
if ( !--count )
promise.emitSuccess();
})
});
});
return promise;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.