From ff46a6c46345e4f8d42037a678bf7a6e8354678c Mon Sep 17 00:00:00 2001 From: THAC0 Date: Fri, 13 Jan 2023 14:51:00 +0000 Subject: [PATCH] refactor: set nunjucks environment globals on load not per request (#361) --- index.js | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/index.js b/index.js index aacff67d..97a913f2 100644 --- a/index.js +++ b/index.js @@ -50,6 +50,17 @@ function fastifyView (fastify, opts, next) { } } + function setupNunjucksEnv (_engine) { + if (type === 'nunjucks') { + const env = _engine.configure(templatesDir, globalOptions) + if (typeof globalOptions.onConfigure === 'function') { + globalOptions.onConfigure(env) + } + return env + } + return null + } + try { templatesDirIsValid(templatesDir) @@ -62,7 +73,7 @@ function fastifyView (fastify, opts, next) { } const dotRender = type === 'dot' ? viewDot.call(fastify, preProcessDot.call(fastify, templatesDir, globalOptions)) : null - const nunjucksEnv = type === 'nunjucks' ? engine.configure(templatesDir, globalOptions) : null + const nunjucksEnv = setupNunjucksEnv(engine) const renders = { ejs: withLayout(viewEjs, globalLayoutFileName), @@ -445,9 +456,6 @@ function fastifyView (fastify, opts, next) { this.send(new Error('Missing page')) return } - if (typeof globalOptions.onConfigure === 'function') { - globalOptions.onConfigure(nunjucksEnv) - } data = Object.assign({}, defaultCtx, this.locals, data) // Append view extension. page = getPage(page, 'njk')