marcusstenbeck
marcusstenbeck

Reputation: 825

How do I render all pages in a page collection on one page?

I'm trying to figure out how to render all the pages in a page collection on a single page. I want all my posts after each other in the generated index.html, like on a blog's front page.

The file structure is

src/
  index.hbs
  posts/
    post-1.hbs
    post-2.hbs
    post-3.hbs

The below does almost what I'm looking for.

<section>
{{#each pages}}
  <article>
    <header>
      <h2>{{data.title}}</h2>
    </header>
    {{page}}
  </article>
{{/each}}
</section>

What am I missing?

Upvotes: 3

Views: 1427

Answers (1)

marcusstenbeck
marcusstenbeck

Reputation: 825

Excuse the quick and dirty answer, I wanted to get it up here as quickly as possible. I'll clean it up in a day or two. (2013-09-26)

After working on this I ended up making a Handlebars helper that I could use in the index.hbs template. With it, I end up with the below Handlebars template for index.hbs.

index.hbs

---
title: Home
---
<p>I'm a dude. I live in Stockholm, and most of the time I work with <a href="http://www.gooengine.com/">Goo</a>.</p>

<section>
  {{#md-posts 'src/posts/*.*'}}
  <article>
    <h2>{{title}}</h2>
    {{#markdown}}
      {{{body}}}
    {{/markdown}}
  </article>
  {{/md-posts}}
</section>

Folder structure

src/
  index.hbs
  posts/
    post-1.hbs
    post-2.hbs
    post-3.md // <--- Markdown with Handlebars 

Gruntfile.coffee

assemble:
  options:
    flatten: true
    layout: 'layouts/default.hbs'
    assets: 'public/assets'
    helpers: 'src/helpers/helper-*.js'
  root: // this is my target
    src: 'src/*.hbs' // <--- Only assemble files at source root level
    dest: 'public/'

src/helpers/helper-md-posts.js

This helper takes a glob expression, reads the files, extracts the YAML front matter, compiles the body source, and finally adds it all to the Handlebars block context. The helper is somewhat misnames, as it doesn't actually compile Markdown... so naming suggestions are welcome.

var glob = require('glob');
var fs = require('fs');
var yamlFront = require('yaml-front-matter');

module.exports.register = function(Handlebars, options) {

  // Customize this helper
  Handlebars.registerHelper('md-posts', function(str, options) {

    var files = glob.sync(str);
    var out = '';
    var context = {};
    var data = null;
    var template = null;

    var _i;
    for(_i = 0; _i < files.length; _i++) {
      data = yamlFront.loadFront(fs.readFileSync(files[_i]), 'src');

      template = Handlebars.compile(data.src); // Compile the source

      context = data; // Copy front matter data to Handlebars context
      context.body = template(data); // render template

      out += options.fn(context);
    }

    return out;
  });

};

See it all in this repo: https://github.com/marcusstenbeck/marcusstenbeck.github.io/tree/source

Upvotes: 3

Related Questions