list_posts.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. 'use strict';
  2. const { url_for } = require('hexo-util');
  3. function listPostsHelper(posts, options) {
  4. if (!options && (!posts || !Object.prototype.hasOwnProperty.call(posts, 'length'))) {
  5. options = posts;
  6. posts = this.site.posts;
  7. }
  8. options = options || {};
  9. const { style = 'list', transform, separator = ', ' } = options;
  10. const orderby = options.orderby || 'date';
  11. const order = options.order || -1;
  12. const className = options.class || 'post';
  13. const amount = options.amount || 6;
  14. // Sort the posts
  15. posts = posts.sort(orderby, order);
  16. // Limit the number of posts
  17. if (amount) posts = posts.limit(amount);
  18. let result = '';
  19. if (style === 'list') {
  20. result += `<ul class="${className}-list">`;
  21. posts.forEach(post => {
  22. const title = post.title || post.slug;
  23. result += `<li class="${className}-list-item">`;
  24. result += `<a class="${className}-list-link" href="${url_for.call(this, post.path)}">`;
  25. result += transform ? transform(title) : title;
  26. result += '</a>';
  27. result += '</li>';
  28. });
  29. result += '</ul>';
  30. } else {
  31. posts.forEach((post, i) => {
  32. if (i) result += separator;
  33. const title = post.title || post.slug;
  34. result += `<a class="${className}-link" href="${url_for.call(this, post.path)}">`;
  35. result += transform ? transform(title) : title;
  36. result += '</a>';
  37. });
  38. }
  39. return result;
  40. }
  41. module.exports = listPostsHelper;