2021-04-28 14:53:46 +02:00
|
|
|
import config from "config";
|
|
|
|
import nunjucks, {Environment} from "nunjucks";
|
|
|
|
|
2021-05-03 19:29:22 +02:00
|
|
|
import ViewEngine from "./ViewEngine.js";
|
|
|
|
|
2021-04-28 14:53:46 +02:00
|
|
|
export default class NunjucksViewEngine extends ViewEngine {
|
|
|
|
private readonly environment: Environment;
|
|
|
|
|
2021-05-04 17:04:14 +02:00
|
|
|
public constructor(targetDir: string, ...additionalViewPaths: string[]) {
|
|
|
|
super(targetDir, 'views', 'njk', false, ...additionalViewPaths);
|
2021-04-28 14:53:46 +02:00
|
|
|
|
|
|
|
const opts = {
|
|
|
|
autoescape: true,
|
|
|
|
noCache: !config.get('view.cache'),
|
|
|
|
throwOnUndefined: true,
|
|
|
|
};
|
|
|
|
this.environment = new nunjucks.Environment([
|
2021-05-04 17:04:14 +02:00
|
|
|
...this.assetPaths.map(path => new nunjucks.FileSystemLoader(path, opts)),
|
2021-04-28 14:53:46 +02:00
|
|
|
], opts);
|
|
|
|
}
|
|
|
|
|
2021-05-04 17:04:14 +02:00
|
|
|
public async preCompile(): Promise<void> {
|
|
|
|
// Nunjucks doesn't need preCompilation or compilation
|
2021-04-28 14:53:46 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
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);
|
|
|
|
});
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|