如何提供"下一篇文章"的链接

cou*_*ing 5 javascript gruntjs assemble

在我正在玩的博客项目中,我有"帖子".这是我的Gruntfile中的汇编块:

assemble: {
  options: {
    layout: ['src/layouts/default.hbs'],
    data: ['src/data/*.{json,yml}']
  },
  pages: {
    src: ['src/posts/**/*.md'],
    dest: 'tmp/posts/'
  }
}    
Run Code Online (Sandbox Code Playgroud)

每个帖子都用markdown表示,带有一些YFM,如下所示:

---
date: '20131129'
latitude: 7.113309999999999
longitude: -73.120468
city: Bucaramanga
country: Colombia


---

# A familiar face...

And then more blog content here...
Run Code Online (Sandbox Code Playgroud)

现在,在我default.hbs,我有标准的东西.我做了一个快速{{inspect page}}来看看我有什么变数.我可以在那里看到,我有一些可能在这件事上有用的信息:

 "index": 46,
 "next": 47,
 "prev":45
Run Code Online (Sandbox Code Playgroud)

我可以想办法通过编写一个自定义手柄助手来处理这个问题,但似乎存在这些变量,这个功能已经存在于某个地方......我只是找不到它.我想到的解决方案似乎过于复杂.

谢谢你!

cou*_*ing 2

我想将其添加为“AN”答案,但希望不是“THE”答案。这是一个把手助手,我把它放在一起,以便吐出下一条路径。这是完整的文件,其中包含注释,可能使它看起来比实际情况更令人生畏。

var _ = require('underscore');

var postPath = function(post){
  //pass a post object in, get back its path for linking
  var out = post['dest'].replace(/^tmp/, '');
  return out;
};

module.exports.register = function (Handlebars, options)  {
  Handlebars.registerHelper('nextPost', function (obj)  {
    var thisPage = obj['page']; // Created a local var for easier reading

    // The "this" object gets passed in as "obj" and contains an array of
    // pages. The trick is, this list isn't necessarily in order, even though
    // the folders are all named by date. Here I sort them. This seems rather
    // heavy handed, as the tax to process these increases exponentially with the
    // number of blog posts.
    // Also, I'm using underscore here to make the code much simpler.
    var sortedPages = _.sortBy(obj['pages'], function(page){ return page['data']['date']; });

    // Go through all of the sorted pages to find the matching data and get the index of where that is,
    // this way we can add one, to find the next element in the sorted array.
    var currentIndex = sortedPages.map(function(page) {return page['data']; }).indexOf(thisPage['data']);
    var nextIndex = currentIndex + 1;
    var out = '';

    // Don't wig out if it's the last one, just return a blank string instead.
    if (nextIndex > (sortedPages.length - 1)){
      out = '';
    }else{
      // Make a pretty path for use in our view
      out = postPath(sortedPages[nextIndex]);
    }
    return  out;
  });

};
Run Code Online (Sandbox Code Playgroud)

其中一些行可以取出并放入它们自己的方法中,以便重新用于“previousPost”辅助方法。但是,这件事有点糟糕,如果有人能帮助我重新整理它,或者为我指出另一个方向,我会很高兴。