Creating Links

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

We can generate pages but currently have no way to show a list of our pages on our homepage.

We are first going to read in the path information and add a url to our meta data.

// /gulpFile.js
...
gulp.task('generate_pages', function() {
  ...
  return gulp.src('contents/pages/**.md')
        .pipe(tap(function(file) {
          // use path library to get file name
          var name = path.basename(file.path, ".md");
          // read meta data contents
          var contents = file.contents.toString();
          var index = contents.indexOf("---");
          // metadata found
          if (index !== -1) {
            var data = JSON.parse(contents.slice(0, index));
            // add url to our meta data
            data.url = "/pages/" + file.relative.replace(".md", ".html");
            // save meta data into object outside stream
            Data.pages[name] = data;
            // replace file contents without meta data
            contents = contents.slice(index+3, contents.length);
            file.contents = new Buffer(contents, "utf-8");
          }
        }))
        ...

We then need to change homepage task to import our pages.

gulp.task('homepage', ['clean', 'generate_pages'], function() {
  return gulp.src("contents/index.hbs")
    .pipe(tap(function(file, t) {
      var template = Handlebars.compile(file.contents.toString());
      var html = template({ 
        title: "Gulp + Handlebars is easy",
        pages: Data.pages
      });
      file.contents = new Buffer(html, "utf-8");
    }))
    .pipe(rename(function(path) {
      path.extname = ".html";
    }))
    .pipe(gulp.dest("build"));
});

Now adjust our index.hbs template to look through our pages.

<!-- /contents/index.hbs -->
<html>
<head>
  <title>Learning Gulp</title>
  <link rel="stylesheet" href="/styles/main.min.css" />
</head>
<body>
  <h1>{{ title }}</h1>

  <ul>
    {{#each pages }}
      <li>
        <a href="{{ url }}">
          {{ title }}
        </a>
      </li>
    {{/each}}
  </ul>
</body>
</html>

Now when we run our gulp task and look at our homepage, we now see the list of pages.

<!-- /build/index.html -->
<html>
<head>
  <title>Learning Gulp</title>
  <link rel="stylesheet" href="/styles/main.min.css" />
</head>
<body>
  <h1>Gulp + Handlebars is easy</h1>

  <ul>
      <li>
        <a href="/pages/first_page.html">
          My First Page
        </a>
      </li>
  </ul>
</body>
</html>
Next: Conclusion