Skip to content

Commit

Permalink
refactor: set nunjucks environment globals on load not per request (#361
Browse files Browse the repository at this point in the history
)
  • Loading branch information
gunjam authored Jan 13, 2023
1 parent 134ff28 commit ff46a6c
Showing 1 changed file with 12 additions and 4 deletions.
16 changes: 12 additions & 4 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand All @@ -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),
Expand Down Expand Up @@ -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')
Expand Down

0 comments on commit ff46a6c

Please sign in to comment.