Собственно я написал, вы покритикуйте, что-нибудь посоветуйте.
Использование.
var nt = require('./native-template');
var session = new cookie.Session(SESSION_NAME, SESSION_LIFETIME);
fetchHeader = nt.render('views/header.htm');
fetchFooter = nt.render('views/footer.htm');
var homeView = nt.render('views/home.htm');
var routes = {
GET: [
['/', function(rq, rs) {
session.start();
rs.writeHead(202, {'content-type': 'text/html; charset=utf-8'});
rs.end( homeView({title: 'Main', name: 'world'}) );
}],
['/index.htm', function(rq, rs) {
rs.writeHead(302, {location: '/'})
rs.end();
}],
['/cookie.htm', function(rq, rs) {
session.start();
rs.end(JSON.stringify(rq.cookie));
}]
],
POST: []
};
Шаблоны
views/home.htm
<%= fetchHeader(vars) %>
<p>Hello, <%= name %></p>
<%= fetchFooter({}) %>
views/header.htm
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
views/footer.htm
</body>
</html>
native-template.js
// [url]http://ejohn.org/blog/javascript-micro-templating/[/url] идею отсюда позаимствовал
var fs = require('fs');
var OPEN_TAG = '<%';
var CLOSING_TAG = '%>';
var cache = {};
function compile(input) {
var output = '';
var startPos = 0;
var endPos;
var data;
while (true) {
endPos = input.indexOf(OPEN_TAG, startPos);
endPos = (endPos > -1) ? endPos : input.length;
if (startPos < endPos) {
output += 'out+="' + input.slice(startPos, endPos).replace(/\r/g, '\\r').
replace(/\n/g, '\\n').replace(/"/g, '\\"') + '"\n';
}
if (endPos == input.length) {
break;
}
startPos = endPos + OPEN_TAG.length;
endPos = input.indexOf(CLOSING_TAG, startPos);
endPos = (endPos < 0) ? input.length : endPos;
data = input.slice(startPos, endPos);
output += ((data[0] == '=') ? 'out+=' + data.slice(1) : data) + '\n';
startPos = endPos + CLOSING_TAG.length;
if (input[startPos] == '\r') {
++startPos;
}
if (input[startPos] == '\n') {
++startPos;
}
}
return output;
}
exports.render = function(filename) {
var source = fs.readFileSync(filename, 'utf-8');
var compiled = compile(source);
return function(obj) {
return new Function('vars', 'var out=""\nwith(vars){' +
compiled + '}\nreturn out')(obj);
}
}