generator.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. 'use strict';
  2. var nunjucks = require('nunjucks');
  3. var env = new nunjucks.Environment();
  4. var pathFn = require('path');
  5. var fs = require('fs');
  6. var gravatar = require('hexo/lib/plugins/helper/gravatar');
  7. env.addFilter('uriencode', function(str) {
  8. return encodeURI(str);
  9. });
  10. env.addFilter('noControlChars', function(str) {
  11. return str.replace(/[\x00-\x1F\x7F]/g, '');
  12. });
  13. var atomTmplSrc = pathFn.join(__dirname, '../atom.xml');
  14. var atomTmpl = nunjucks.compile(fs.readFileSync(atomTmplSrc, 'utf8'), env);
  15. var rss2TmplSrc = pathFn.join(__dirname, '../rss2.xml');
  16. var rss2Tmpl = nunjucks.compile(fs.readFileSync(rss2TmplSrc, 'utf8'), env);
  17. module.exports = function(locals) {
  18. var config = this.config;
  19. var feedConfig = config.feed;
  20. var template = feedConfig.type === 'rss2' ? rss2Tmpl : atomTmpl;
  21. var posts = locals.posts.sort('-date');
  22. posts = posts.filter(function(post) {
  23. return post.draft !== true;
  24. });
  25. if (feedConfig.limit) posts = posts.limit(feedConfig.limit);
  26. var url = config.url;
  27. if (url[url.length - 1] !== '/') url += '/';
  28. var icon;
  29. if (config.email) icon = gravatar(config.email);
  30. var xml = template.render({
  31. config: config,
  32. url: url,
  33. icon: icon,
  34. posts: posts,
  35. feed_url: config.root + feedConfig.path
  36. });
  37. return {
  38. path: feedConfig.path,
  39. data: xml
  40. };
  41. };