Markdown and Handlebars to make pages

Learning Gulp : part 19 of 22 published on Aug 10, 2015

Now to combine our Handlebars template skills with our markdown conversion tasks.

First we will create a Handlebar template to use with all our pages.

<!-- /contents/page.hbs -->
<!DOCTYPE html>
<html>
<head>
  <link rel="stylesheet" href="/styles/main.min.css" />
</head>
<body>
  <a href="/">Back to Home</a>
  {{{ contents }}}
</body>
</html>
  • Notice the change from {{ }} to {{{ }}}. Handlebars escapes the contents in {{ }}. So using the three {{{ }}} method tells Handlebars to not escape the contents.

We will then use this template in our generate_pages task.

gulp.task('generate_pages', function() {
  // read the template from page.hbs
  return gulp.src('contents/page.hbs')
    .pipe(tap(function(file) {
      // file is page.hbs so generate template from file
      var template = Handlebars.compile(file.contents.toString());

      // now read all the pages from the pages directory
      return gulp.src('contents/pages/**.md')
        // convert from markdown
        .pipe(markdown())
        .pipe(tap(function(file) {
          // file is the converted HTML from the markdown
          // set the contents to the contents property on data
          var data = {
            contents: file.contents.toString()
          };
          // we will pass data to the Handlebars template to create the actual HTML to use
          var html = template(data);
          // replace the file contents with the new HTML created from the Handlebars template + data object that contains the HTML made from the markdown conversion
          file.contents = new Buffer(html, "utf-8");
        }))
        .pipe(gulp.dest('build/pages'));
    }));
});

When we run our gulp task:

$ gulp generate_pages
Using gulpfile ~/YOUR_DIRECTORY/gulpFile.js
Starting 'generate_pages'...
Finished 'generate_pages' after 17 ms

We should see our pages created using the Handlebars template.

<!-- /build/pages/first_page.html -->
<!DOCTYPE html>
<html>
<head>
  <link rel="stylesheet" href="/styles/main.min.css" />
</head>
<body>
  <a href="/">Back to Home</a>
<h1 id="isn-t-markdown-great-">Isn&#39;t markdown great!</h1>
<p>Yes, it makes a <strong>bold</strong> statement.</p>

</body>
</html>
Next: Reading Metadata for Posts