sync/src/web/pug.js

84 lines
2.1 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");
2018-03-05 21:46:58 -08:00
const cache = new Map();
const LOGGER = require('@calzoneman/jsli')('web/pug');
/**
* 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);
2018-03-05 21:46:58 -08:00
let renderFn = cache.get(view);
if (!renderFn || Config.get("debug")) {
LOGGER.debug("Loading template %s", view);
var file = path.join(templates, view + ".pug");
2018-03-05 21:46:58 -08:00
renderFn = 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")
});
2018-03-05 21:46:58 -08:00
cache.set(view, renderFn);
}
2018-03-05 21:46:58 -08:00
res.send(renderFn(merge(locals, res)));
}
function nvl(a, b) {
if (typeof a === 'undefined') return b;
return a;
}
2018-03-05 21:46:58 -08:00
function clearCache() {
let removed = 0;
for (const key of cache.keys()) {
cache.delete(key);
removed++;
}
LOGGER.info('Removed %d compiled templates from the cache', removed);
}
module.exports = {
2018-03-05 21:46:58 -08:00
sendPug: sendPug,
clearCache: clearCache
};