Compile both partials and markdown based on a Handlebars template with Gulp

1.4k views Asked by At

I have a Handlebars template here called tpage.hbs:

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Title</title>
  {{> head}}
</head>
<body>
  {{> home-header}}
  {{{ mdcontents }}}
</body>
</html>

head and home-header are partials.

I have a folder of Markdown files, and I want to make HTML pages based on this template, adding the .md files in where mdcontents is in the template.

I have the following Gulpfile:

var gulp = require('gulp');

var handlebars = require('gulp-compile-handlebars');
var HB = require('Handlebars'); // I know I don't need two Handlebars imports, I'm just trying different things at this point
var uglify = require('gulp-uglify');
var markdown = require('gulp-markdown');
var tap = require('gulp-tap');

// ...

gulp.task('markhb', function() {
  return gulp.src('./app/templates/tpage.hbs')
    .pipe(handlebars({}, {
      ignorePartials: false,
      batch: ['./app/templates/partials'] /* my partials directory */
    }))
    .pipe(tap(function(file) {
      var template = HB.compile(file.contents.toString());
      console.log(file.contents.toString());

      return gulp.src('./app/content/mdpages/**.md')
        .pipe(markdown())
        .pipe(tap(function(file) {
          var data = {
            mdcontents: file.contents.toString()
          };

          var html = template(data);

          file.contents = new Buffer(html, 'utf-8'); // Buffer() is deprecated, I'll fix that later
        }))
        .pipe(rename({
          extname: '.html'
        }))
        .pipe(gulp.dest('build/pages'));
    }));
});

So, my issue is that if I keep the first pipe call, it loads up the partials just fine, but it ignores and strips out mdcontents completely. But, if I remove that first pipe call, it renders the markdown just fine, but strips out the partials. I don't like that I'm using two Handlebars libraries right now either, but at this point I just want a working template before I clean up. What do I need to add, remove, or change to get both the partials and markdown to render?

1

There are 1 answers

0
Graham P Heath On

Use a Handlebars markdown middleware like this one https://github.com/helpers/helper-markdown.

Then the idea is to include the file using Handlebars with helper-markdown as a filter, not to have gulp do the processing for you.