Skip to content

Instantly share code, notes, and snippets.

@tameemsafi
Last active October 1, 2020 05:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tameemsafi/a10feb4bec808cb531b4b8a2967ba652 to your computer and use it in GitHub Desktop.
Save tameemsafi/a10feb4bec808cb531b4b8a2967ba652 to your computer and use it in GitHub Desktop.
Adding global variables functions to nunjucks
// 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