Skip to content

Instantly share code, notes, and snippets.

@aljopro
Created June 10, 2017 12:07
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save aljopro/b104e52471abce17557ba10aa074a59a to your computer and use it in GitHub Desktop.
Static Site Generator using Gulp, Nunjucks, and Markdown with Front Matter
const gulp = require('gulp');
const nunjucksRender = require('gulp-nunjucks-render');
const gulpGrayMatter = require('gulp-gray-matter');
const debug = require('gulp-debug');
const markdown = require('gulp-markdown');
const data = require('gulp-data');
const through = require('through2');
const fs = require('fs');
const path = require('path');
function getTemplate() {
const templateCache = {};
return through.obj((file, enc, cb) => {
let templatePath = path.join('./templates', file.data.template);
let template = templateCache[templatePath];
if(!template) {
template = fs.readFileSync(templatePath);
templateCache[templatePath] = template;
}
let filePath = file.path;
if(file.data.path) {
filePath = path.join(path.dirname(file.path), file.data.path);
}
file.path = filePath;
file.contents = new Buffer(template);
cb(null, file);
});
}
function getDataForFile(file) {
let data = file.data;
data.contents = file.contents.toString();
return data;
}
gulp.task('default', function() {
return gulp.src('./pages/**.*')
.pipe(gulpGrayMatter())
.pipe(markdown())
.pipe(data(getDataForFile))
.pipe(getTemplate())
.pipe(nunjucksRender({
path: './templates'
}))
.pipe(gulp.dest('./dist'));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment