Last active
October 1, 2020 05:04
-
-
Save tameemsafi/a10feb4bec808cb531b4b8a2967ba652 to your computer and use it in GitHub Desktop.
Adding global variables functions to nunjucks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Create express server | |
const app = express(); | |
// Create nunjucks fileloader instance for the views folder | |
const nunjucksFileLoader = new nunjucks.FileSystemLoader(path.resolve('/path/to/views/folder'), { | |
noCache: true, | |
}); | |
// Create a nunjucks instance to be used for the view engine | |
// This instance can be used to add filters and globals | |
let env = new nunjucks.Environment(nunjucksFileLoader, { | |
autoescape: false, | |
web: { | |
useCache: false, | |
}, | |
}); | |
// Add lodash as a | |
// global for view templates | |
env.addGlobal('_', _); | |
// Loops through views/parials | |
// folder and get full path for each file | |
const getMacroFilePaths = async () => { | |
// Creates a promise since the function uses a callback | |
return new Promise((resolve, reject) => { | |
nodeDir.paths(path.resolve(CONFIG.paths.views.base, 'macros'), (err, paths) => { | |
// Handles error | |
if (err) { | |
// Returns a reject promise response | |
return reject(err); | |
} | |
// Returns a resolved promise resonse | |
return resolve(paths.files); | |
}); | |
}); | |
}; | |
// Add all macro file paths to be accessible inside view templates | |
env.addGlobal('macroFilePaths', await getMacroFilePaths()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment