Top features added HEXO

Reference https://zhwhong.cn/2017/03/23/deal-with-hexo-article-top-problem/

Principle: When Hexo generation Home HTML, the high value of the top article standing in the front, reached top function.

Modify node_modules / hexo-generator-index / lib / generator.js Hexo folder, carried articles top value sort before generating article.

Need to add code:

posts.data = posts.data.sort(function(a, b) {
    if(a.top && b.top) { // 两篇文章top都有定义
        if(a.top == b.top) return b.date - a.date; // 若top值一样则按照文章日期降序排
        else return b.top - a.top; // 否则按照top值降序排
    }
    else if(a.top && !b.top) { // 以下是只有一篇文章top有定义,那么将有top的排在前面(这里用异或操作居然不行233)
        return -1;
    }
    else if(!a.top && b.top) {
        return 1;
    }
    else return b.date - a.date; // 都没定义按照文章日期降序排
});

After editing, only need to set the value to be topped top article in the front-matter, the order will be selected top front top larger values ​​according to the size of the top values. It should be noted that the file is not part of this subject matter, nor is Git management, backup time is easier to ignore.

The following is the final generator.js content

'use strict';
var pagination = require('hexo-pagination');
module.exports = function(locals) {
  var config = this.config;
  var posts = locals.posts.sort(config.index_generator.order_by);
  posts.data = posts.data.sort(function(a, b) {
      if(a.top && b.top) {
          if(a.top == b.top) return b.date - a.date;
          else return b.top - a.top;
      }
      else if(a.top && !b.top) {
          return -1;
      }
      else if(!a.top && b.top) {
          return 1;
      }
      else return b.date - a.date;
  });
  var paginationDir = config.pagination_dir || 'page';
  return pagination('', posts, {
    perPage: config.index_generator.per_page,
    layout: ['index', 'archive'],
    format: paginationDir + '/%d/',
    data: {
      __index: true
    }
  });
};

Guess you like

Origin www.cnblogs.com/lqerio/p/11117467.html