swaf/src/components/NunjucksComponent.ts

59 lines
1.9 KiB
TypeScript
Raw Normal View History

2020-04-23 11:18:23 +02:00
import nunjucks from "nunjucks";
import config from "config";
import {Express, Router} from "express";
import ApplicationComponent from "../ApplicationComponent";
import Controller from "../Controller";
import {ServerError} from "../HttpError";
export default class NunjucksComponent extends ApplicationComponent<void> {
private readonly viewsPath: string;
constructor(viewsPath: string = 'views') {
super();
this.viewsPath = viewsPath;
}
2020-04-23 11:18:23 +02:00
public async start(app: Express, router: Router): Promise<void> {
2020-07-08 11:09:27 +02:00
let coreVersion = 'unknown';
try {
coreVersion = require('../../package.json').version;
} catch (e) {
try {
coreVersion = require('../package.json').version;
} catch (e) {
}
}
const env = nunjucks.configure(this.viewsPath, {
2020-04-23 11:18:23 +02:00
autoescape: true,
express: app,
noCache: !config.get('view.cache'),
throwOnUndefined: true,
})
.addGlobal('route', (route: string, params: { [p: string]: string } | [] = [], absolute: boolean = false) => {
const path = Controller.route(route, params, absolute);
if (path === null) throw new ServerError(`Route ${route} not found.`);
return path;
})
.addGlobal('app_version', this.app!.getVersion())
2020-07-08 11:09:27 +02:00
.addGlobal('core_version', coreVersion)
2020-04-23 11:18:23 +02:00
.addFilter('hex', (v: number) => {
return v.toString(16);
});
app.set('view engine', 'njk');
router.use((req, res, next) => {
req.env = env;
res.locals.url = req.url;
res.locals.params = () => req.params;
2020-06-27 17:11:31 +02:00
res.locals.app = config.get('app');
2020-04-23 11:18:23 +02:00
next();
});
}
public async stop(): Promise<void> {
}
}