forked from jazzychad/template.node.js
-
Notifications
You must be signed in to change notification settings - Fork 3
/
template.js
40 lines (33 loc) · 1017 Bytes
/
template.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/*
* template.node.js
* by Chad Etzel - MIT Licensed
*
* Based off of:
* Simple JavaScript Templating
* by John Resig - http://ejohn.org/ - MIT Licensed
* http://ejohn.org/blog/javascript-micro-templating/
*/
var fs = require("fs");
var cache = {};
var create = function(file_name, callback) {
fs.readFile(file_name, function(err, file_contents) {
if(!err) {
callback(new Function("obj",
"var p=[],print=function(){p.push.apply(p,arguments);};" +
// Introduce the data as local variables using with(){}
"with(obj){p.push('" +
// Convert the template into pure JavaScript
file_contents
.replace(/[\r\n\t]/g, " ")
.split("<%").join("\t")
.replace(/((^|%>)[^\t]*)'/g, "$1\r")
.replace(/\t=(.*?)%>/g, "',$1,'")
.split("\t").join("');")
.split("%>").join("p.push('")
.split("\r").join("\\'")
+ "');}return p.join('');"));
}
});
}
/* exports */
exports.create = create;