list_posts.js 1.5 KB

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