I want to read in a template, then read in zero or more files that contain content to inject into the template. The template and content are all in Markdown. From a small amount of reasearch it looks like Swig will provide a lightweight markup that I can use
The resulting function will look something like this:
function assembleCharacterDocument(slug) {
return gulp.src('./templates/character-document.md')
.pipe(files2obj(['characters/'+slug+'/*.md'])) // read content for the character
.pipe(swig()) // == require('gulp-swig'); inject content into template
.pipe(md2pdf()) // convert Markdown to PDF - outside scope of this question
.pipe(gulp.dest('./products/characters/'+slug+'.pdf'));
});
Since Swig takes a plain-old object for its replacement data, I want each file that comes in to have its filename as its key in the object. So, for example, my replacement data object will look something like this:
{
"bio": content of characters/{slug}/bio.md,
"profile": content of characters/{slug}/profile.md,
"timeline": content of characters/{slug}/timeline.md,
etc.
}
What is the content of files2obj()
?
I ended up forgoing Gulp piping and just used the fs
filesystem methods directly to fulfill my task. (Dependencies omitted for brevity.)
var templatePath = './templates/character-document.md';
var sourcePath = path.join("characters",charSlug);
var targetCombinedMarkdownPath = path.join('products',charSlug+'.md');
fs.readdir(sourcePath,function (err, files) {
if (err) { throw err; }
var data = {};
files.forEach(function(f) {
var check = /^(.*).md$/.exec(f);
if (check) {
data[check[1]] = fs.readFileSync(path.join(sourcePath,f),'utf8');
}
});
var engine = swig.compileFile(templatePath);
var combined = engine(data);
fs.writeFileSync(targetCombinedMarkdownPath, combined);
md2pdf({
title: data.name || "CHARACTER NAME MISSING",
source: [targetCombinedMarkdownPath],
targetFilename: charSlug
});
});