For generating my blog I need to load all the partials templates into variables of particular names so I can feed them into my Mustache templates.
First I load all the files in my partials directory into an array of filenames. I strip the file extension from them so I have all the strings I want to use as my variable names:
const partialFiles = fs.readdirSync('./partials/').reduce((partials, file) => {
const ext = path.extname(file)
if (ext=='.mustache') {
return partials.concat(path.basename(file, ext))
}
return partials
}, [])
partialFiles
Now I want to load the contents of each of these files into a variable of the same name. Well, since these names have '-' character in them I could never really do that, but that doesn't really matter in this case because I can stick them all in an object and have the filenames as the key and my file contents as the value.
function getPartialTemplate(partialFileName) {
return fs.readFileSync(path.join(__dirname, 'partials', `${partialFileName}.mustache`)).toString()
}
function addPartialTemplate(obj, partialFileName) {
return Object.assign(obj, {
[partialFileName]: getPartialTemplate(partialFileName)
})
}
const partials = partialFiles.reduce(addPartialTemplate, {})
partials['web-page-meta']
partials.post
This object can now be passed to Mustache and the partials can be identified by their filename without me having to specify names anywhere in the code. This is handy because as I add more partials I won't need to change the code - just make adjustments to my template files.