35 lines
1.2 KiB
TypeScript
35 lines
1.2 KiB
TypeScript
|
import ViewEngine from "./ViewEngine";
|
||
|
import config from "config";
|
||
|
import nunjucks, {Environment} from "nunjucks";
|
||
|
|
||
|
export default class NunjucksViewEngine extends ViewEngine {
|
||
|
private readonly environment: Environment;
|
||
|
|
||
|
public constructor(devWatchedViewDir: string, ...additionalViewPaths: string[]) {
|
||
|
super(devWatchedViewDir, ...additionalViewPaths);
|
||
|
|
||
|
const opts = {
|
||
|
autoescape: true,
|
||
|
noCache: !config.get('view.cache'),
|
||
|
throwOnUndefined: true,
|
||
|
};
|
||
|
this.environment = new nunjucks.Environment([
|
||
|
...this.viewPaths.map(path => new nunjucks.FileSystemLoader(path, opts)),
|
||
|
], opts);
|
||
|
}
|
||
|
|
||
|
public getExtension(): string {
|
||
|
return 'njk';
|
||
|
}
|
||
|
|
||
|
public async render(file: string, locals: Record<string, unknown>): Promise<string> {
|
||
|
return await new Promise<string>((resolve, reject) => {
|
||
|
this.environment.render(file, locals, (err, res) => {
|
||
|
if (err) return reject(err);
|
||
|
else if (res === null) reject('Null response from nunjucks environment.render()');
|
||
|
else return resolve(res);
|
||
|
});
|
||
|
});
|
||
|
}
|
||
|
}
|