swaf/src/components/NunjucksComponent.ts

76 lines
2.6 KiB
TypeScript
Raw Normal View History

import nunjucks, {Environment} from "nunjucks";
2020-04-23 11:18:23 +02:00
import config from "config";
import {Express, Router} from "express";
2020-04-23 11:18:23 +02:00
import ApplicationComponent from "../ApplicationComponent";
import Controller from "../Controller";
import {ServerError} from "../HttpError";
import * as querystring from "querystring";
2020-07-15 11:42:49 +02:00
import {ParsedUrlQueryInput} from "querystring";
import * as util from "util";
import * as path from "path";
2020-04-23 11:18:23 +02:00
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> {
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) {
}
}
this.env = new nunjucks.Environment([
...this.viewsPath.map(path => new nunjucks.FileSystemLoader(path)),
new nunjucks.FileSystemLoader(path.join(__dirname, '../../../views')),
new nunjucks.FileSystemLoader(path.join(__dirname, '../views')),
2020-07-12 11:46:21 +02:00
], {
2020-04-23 11:18:23 +02:00
autoescape: true,
noCache: !config.get('view.cache'),
throwOnUndefined: true,
})
2020-07-15 11:42:49 +02:00
.addGlobal('route', (route: string, params?: { [p: string]: string } | [], query?: ParsedUrlQueryInput, absolute?: boolean) => {
const path = Controller.route(route, params, query, absolute);
2020-04-23 11:18:23 +02:00
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)
.addGlobal('querystring', querystring)
.addGlobal('app', config.get('app'))
.addFilter('dump', (val) => {
return util.inspect(val);
})
2020-04-23 11:18:23 +02:00
.addFilter('hex', (v: number) => {
return v.toString(16);
});
this.env.express(app);
2020-04-23 11:18:23 +02:00
app.set('view engine', 'njk');
}
2020-04-23 11:18:23 +02:00
public async init(router: Router): Promise<void> {
2020-04-23 11:18:23 +02:00
router.use((req, res, next) => {
req.env = this.env!;
2020-04-23 11:18:23 +02:00
res.locals.url = req.url;
2020-07-15 11:42:49 +02:00
res.locals.params = req.params;
res.locals.query = req.query;
res.locals.body = req.body;
2020-06-27 17:11:31 +02:00
2020-04-23 11:18:23 +02:00
next();
});
}
public getEnv(): Environment | undefined {
return this.env;
}
2020-04-23 11:18:23 +02:00
}