Add NunjucksComponent
This commit is contained in:
parent
1c661cee5e
commit
6469de499f
38
src/components/NunjucksComponent.ts
Normal file
38
src/components/NunjucksComponent.ts
Normal file
@ -0,0 +1,38 @@
|
|||||||
|
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> {
|
||||||
|
public async start(app: Express, router: Router): Promise<void> {
|
||||||
|
const env = nunjucks.configure('views', {
|
||||||
|
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', require('../package.json').version)
|
||||||
|
.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;
|
||||||
|
next();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public async stop(): Promise<void> {
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user