1 var pug = require("pug");
2 var fs = require("fs");
3 var path = require("path");
4 var Config = require("../config");
5 var templates = path.join(__dirname, "..", "..", "templates");
7 const cache = new Map();
8 const LOGGER = require('@calzoneman/jsli')('web/pug');
11 * Merges locals with globals for pug rendering
13 function merge(locals, res) {
15 siteTitle: Config.get("html-template.title"),
16 siteDescription: Config.get("html-template.description"),
17 csrfToken: typeof res.req.csrfToken === 'function' ? res.req.csrfToken() : '',
18 baseUrl: getBaseUrl(res),
19 channelPath: Config.get("channel-path"),
21 if (typeof locals !== "object") {
24 for (var key in locals) {
25 _locals[key] = locals[key];
30 function getBaseUrl(res) {
32 return req.realProtocol + "://" + req.header("host");
36 * Renders and serves a pug template
38 function sendPug(res, view, locals) {
42 locals.loggedIn = nvl(locals.loggedIn, res.locals.loggedIn);
43 locals.loginName = nvl(locals.loginName, res.locals.loginName);
44 locals.superadmin = nvl(locals.superadmin, res.locals.superadmin);
46 let renderFn = cache.get(view);
48 if (!renderFn || Config.get("debug")) {
49 LOGGER.debug("Loading template %s", view);
51 var file = path.join(templates, view + ".pug");
52 renderFn = pug.compile(fs.readFileSync(file), {
54 pretty: !Config.get("http.minify")
57 cache.set(view, renderFn);
60 res.send(renderFn(merge(locals, res)));
64 if (typeof a === 'undefined') return b;
68 function clearCache() {
71 for (const key of cache.keys()) {
76 LOGGER.info('Removed %d compiled templates from the cache', removed);
81 clearCache: clearCache