75 lines
2.4 KiB
TypeScript
75 lines
2.4 KiB
TypeScript
import nunjucks, {Environment} from "nunjucks";
|
|
import config from "config";
|
|
import {Express, Router} from "express";
|
|
import ApplicationComponent from "../ApplicationComponent";
|
|
import Controller from "../Controller";
|
|
import {ServerError} from "../HttpError";
|
|
import * as querystring from "querystring";
|
|
import {ParsedUrlQueryInput} from "querystring";
|
|
import * as util from "util";
|
|
|
|
export default class NunjucksComponent extends ApplicationComponent<void> {
|
|
private readonly viewsPath: string;
|
|
private env?: Environment;
|
|
|
|
public constructor(viewsPath: string = 'views') {
|
|
super();
|
|
this.viewsPath = viewsPath;
|
|
}
|
|
|
|
public async start(app: Express): Promise<void> {
|
|
let coreVersion = 'unknown';
|
|
try {
|
|
coreVersion = require('../../package.json').version;
|
|
} catch (e) {
|
|
try {
|
|
coreVersion = require('../package.json').version;
|
|
} catch (e) {
|
|
}
|
|
}
|
|
|
|
this.env = nunjucks.configure([
|
|
this.viewsPath,
|
|
'views',
|
|
'node_modules/wms-core/views'
|
|
], {
|
|
autoescape: true,
|
|
express: app,
|
|
noCache: !config.get('view.cache'),
|
|
throwOnUndefined: true,
|
|
})
|
|
.addGlobal('route', (route: string, params?: { [p: string]: string } | [], query?: ParsedUrlQueryInput, absolute?: boolean) => {
|
|
const path = Controller.route(route, params, query, absolute);
|
|
if (path === null) throw new ServerError(`Route ${route} not found.`);
|
|
return path;
|
|
})
|
|
.addGlobal('app_version', this.app!.getVersion())
|
|
.addGlobal('core_version', coreVersion)
|
|
.addGlobal('querystring', querystring)
|
|
.addGlobal('app', config.get('app'))
|
|
|
|
.addFilter('dump', (val) => {
|
|
return util.inspect(val);
|
|
})
|
|
.addFilter('hex', (v: number) => {
|
|
return v.toString(16);
|
|
});
|
|
app.set('view engine', 'njk');
|
|
}
|
|
|
|
public async init(router: Router): Promise<void> {
|
|
router.use((req, res, next) => {
|
|
req.env = this.env!;
|
|
res.locals.url = req.url;
|
|
res.locals.params = req.params;
|
|
res.locals.query = req.query;
|
|
res.locals.body = req.body;
|
|
|
|
next();
|
|
});
|
|
}
|
|
|
|
public getEnv(): Environment | undefined {
|
|
return this.env;
|
|
}
|
|
} |