swaf/src/frontend/NunjucksViewEngine.ts

36 lines
1.2 KiB
TypeScript

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