I am using nunjucks-render as a front-end JavaScript templating engine.
I would like to read frontal matter data out of certain .nunjuck files and then use that data whilst compiling my .nunjuck (template) files into .html files.
After a bit of research I have found gulp-gray-matter to be one of the faster and better frontal matter extraction plugins.
My question is: How do I now get access to the frontal matter data objects?
For example, I would write the frontal matter in a .nunjucks file as:
---
title: Welcome to ACME Co.
---
<title>{{ data.title }}</title>
Final HTML output should be:
<title>Welcome to ACME Co.</title>
My gulfile.js settings are as follows:
var gulp = require('gulp'),
nunjucks = require('gulp-nunjucks-render')
gulpGrayMatter = require('gulp-gray-matter');
gulp.task("nunjucks", function(){
return gulp.src(src/templates/**/*.+(nunjucks|njk))
.pipe(gulpGrayMatter()) //send files through gray-matter plugin to extract frontal-matter
.pipe(nunjucks({
path: src/templates
}))
.pipe(gulp.dest(src));
});
By default gulp-gray-matter
stores all front matter data in the data
property of each file in your stream.
Also by default gulp-nunjucks-render
uses the data that is present in the data
property of each file in your stream.
So you don't actually have to do anything fancy in your Gulpfile. This will work:
gulp.task('nunjucks', function(){
return gulp.src('src/templates/**/*.nunjucks')
.pipe(gulpGrayMatter())
.pipe(nunjucks())
.pipe(gulp.dest('dest'));
});
You do have to correctly access the data in your .nunjuck
templates however:
---
title: Welcome to ACME Co.
---
<title>{{ title }}</title>