sync/src/web/pug.js

65 lines
1.7 KiB
JavaScript
Raw Normal View History

var pug = require("pug");
var fs = require("fs");
var path = require("path");
var Config = require("../config");
var templates = path.join(__dirname, "..", "..", "templates");
var cache = {};
/**
* Merges locals with globals for pug rendering
*/
2015-02-15 21:56:00 -06:00
function merge(locals, res) {
var _locals = {
siteTitle: Config.get("html-template.title"),
siteDescription: Config.get("html-template.description"),
2014-02-26 10:50:59 -06:00
siteAuthor: "Calvin 'calzoneman' 'cyzon' Montgomery",
2015-11-02 21:13:02 -08:00
csrfToken: typeof res.req.csrfToken === 'function' ? res.req.csrfToken() : '',
baseUrl: getBaseUrl(res),
channelPath: Config.get("channel-path"),
};
if (typeof locals !== "object") {
return _locals;
}
for (var key in locals) {
_locals[key] = locals[key];
}
return _locals;
}
2015-08-12 20:00:52 -07:00
function getBaseUrl(res) {
var req = res.req;
return req.realProtocol + "://" + req.header("host");
2015-08-12 20:00:52 -07:00
}
/**
* Renders and serves a pug template
*/
function sendPug(res, view, locals) {
if (!locals) {
locals = {};
}
locals.loggedIn = nvl(locals.loggedIn, res.locals.loggedIn);
locals.loginName = nvl(locals.loginName, res.locals.loginName);
locals.superadmin = nvl(locals.superadmin, res.locals.superadmin);
if (!(view in cache) || Config.get("debug")) {
var file = path.join(templates, view + ".pug");
var fn = pug.compile(fs.readFileSync(file), {
2013-12-25 16:18:21 -05:00
filename: file,
2014-02-23 23:27:07 -06:00
pretty: !Config.get("http.minify")
});
cache[view] = fn;
}
2015-02-15 21:56:00 -06:00
var html = cache[view](merge(locals, res));
res.send(html);
}
function nvl(a, b) {
if (typeof a === 'undefined') return b;
return a;
}
module.exports = {
sendPug: sendPug
};