summaryrefslogblamecommitdiffstats
path: root/lib/templates.js
blob: c47045495de19afb6f56ff73ec572349efba1e1a (plain) (tree)













































                                                                                      
var nun = require('nun');

var templates = {};

var render = function(template, args, callback) {
    if (template in templates) {
        callback(undefined, templates[template](args));
    }
    else {
        nun.compile(__dirname + '/../templates/' + template, "", function(err, tmpl) {
            if (err) {
                callback(err);
            }
            else {
                templates[template] = tmpl;
                callback(err, tmpl(args));
            }
        });
    }
};

var renderHtml = function(template, args, res) {
    render(template, args, function(err, events) {
        if (err) {
            res.writeHead(500, {'Content-Type': 'text/plain'});
            res.write(JSON.stringify(err));
            res.end('\n');
        }
        else {
            res.writeHead(200, {'Content-Type': 'text/html'});

            events.on('data', function(data) {
                res.write(data);
            });

            events.on('end', function() {
                res.end('\n');
            });
        }
    });
};

module.exports = {
    render: render,
    renderHtml: renderHtml
};