如何提供指向'下一篇文章'

How to provide a link to the 'next post'

本文关键字:一篇 文章 何提供      更新时间:2024-02-13

在我正在玩的一个博客项目中,我有"帖子"。这是我的Gruntfile的组装块:

assemble: {
  options: {
    layout: ['src/layouts/default.hbs'],
    data: ['src/data/*.{json,yml}']
  },
  pages: {
    src: ['src/posts/**/*.md'],
    dest: 'tmp/posts/'
  }
}    

每个帖子都用降价表示,并加上一点YFM,就像这样:

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

---
# A familiar face...
And then more blog content here...

现在,在我的default.hbs中,我有了标准的东西。我做了一个快速的{检查页面}},看看我手头有什么变量。我可以在那里看到,我有一些信息可能对这件事有用:

 "index": 46,
 "next": 47,
 "prev":45

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

谢谢大家!

我们最近在上下文中添加了一个分页对象,但它现在只根据源文件名进行排序。

@jonschlinkert还创建了一个可能对您有用的助手。。。https://github.com/helpers/handlebars-helper-paginate

我们现在正在进行汇编的重构,我们想做的一件事是让这些类型的东西更容易工作,而不必创建这样的自定义助手。我喜欢你的代码,因为它展示了如何使用下划线/lodash按其他属性对页面进行排序。

我想把它添加为"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;
  });
};

其中的一些行可以被取出并放入它们自己的方法中,以便重用"previousPost"辅助方法。但是,这件事有点臭,如果有人能帮我梳洗一下,或者给我指明另一个方向,我会很高兴的。