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 { // Nunjucks doesn't need preCompilation or compilation } public async render(file: string, locals: Record): Promise { return await new Promise((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); }); }); } }