Gulp Front Matter +Markdown through Nunjucks
Asked Answered
R

2

6

I'm working on adding some simple Markdown processing to my Gulp process, but I can't quite get the pieces to work together. I seem to be missing the step between getting the front matter content, and determining which Nunjuck template to apply.

Here's the section in my Gulp file:

gulp.task('pages:md', function() {
  gulp.src('./content/**/*.md')
    .pipe(frontMatter({ // optional configuration
      property: 'frontMatter', // property added to file object
      remove: true // should we remove front-matter header?
    }))
    .pipe(marked({
        // optional : marked options
    }))
    .pipe(nunjucks({
      // ?? Feels like I need to specify which template applies based on the front matter "layout" property?
    }))
    .pipe(gulp.dest('build/'))
});

The markdown file looks like this:

---
title: Title
layout: layout.html
nav_active: home
---

...markdown content...

I feel like it's going the right direction but being able to visualise where that front matter data has gone, and how to expose it to the Nunjucks rendering, is not clear. Any help?

Remission answered 27/9, 2015 at 16:18 Comment(2)
How did you go @don-h. Did you get your pipe to work?Pick
Hey @Pick in the end I got frustrated by the process, and went with Metalsmith. Does what I need quite well.Remission
D
7

You need gulp-wrap and original nunjucks.

gulp-nunjucks is a tool for compiling the stream of nunjucks templates, but what you need to do is to wrap your contents in a nunjucks template and that is what gulp-wrap is for.

Try npm install gulp-wrap nunjucks in addition to other settings and then the following should work.

gulpfile

var gulp = require('gulp')
var wrap = require('gulp-wrap')
var frontMatter = require('gulp-front-matter')
var marked = require('gulp-marked')

var fs = require('fs')

gulp.task('pages:md', function() {
  gulp.src('./content/**/*.md')
    .pipe(frontMatter())
    .pipe(marked())
    .pipe(wrap(function (data) {
      return fs.readFileSync('path/to/layout/' + data.file.frontMatter.layout).toString()
    }, null, {engine: 'nunjucks'}))
    .pipe(gulp.dest('build/'))
});

markdown

---
title: Title
layout: layout.nunjucks
nav_active: home
---

...markdown content...

layout.nunjucks

<h1>{{ file.frontMatter.title }}</h1>

<p>{{ contents }}</p>
Downcomer answered 6/1, 2016 at 5:3 Comment(0)
T
2

You might want to have a look a the plugin gulp-ssg. I don't know what it's worth, but it was mentionned in this issue for someone who had the same problem as you.

Not exactly what you're looking, but for this kind of work, I've had success using metalsmith. You can even mix it with gulp if, like me, you have more complex processing for your javascripts resources for example.

Triplicate answered 27/9, 2015 at 19:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.