renderer.js 962 B

12345678910111213141516171819202122232425262728293031323334353637
  1. /* global hexo */
  2. 'use strict';
  3. const nunjucks = require('nunjucks');
  4. const path = require('path');
  5. function njkCompile(data) {
  6. const templateDir = path.dirname(data.path);
  7. const env = nunjucks.configure(templateDir, {
  8. autoescape: false
  9. });
  10. env.addFilter('attr', (dictionary, key, value) => {
  11. dictionary[key] = value;
  12. return dictionary;
  13. });
  14. env.addFilter('json', dictionary => {
  15. return JSON.stringify(dictionary || '');
  16. });
  17. return nunjucks.compile(data.text, env, data.path);
  18. }
  19. function njkRenderer(data, locals) {
  20. return njkCompile(data).render(locals);
  21. }
  22. // Return a compiled renderer.
  23. njkRenderer.compile = function(data) {
  24. const compiledTemplate = njkCompile(data);
  25. // Need a closure to keep the compiled template.
  26. return function(locals) {
  27. return compiledTemplate.render(locals);
  28. };
  29. };
  30. hexo.extend.renderer.register('njk', 'html', njkRenderer);
  31. hexo.extend.renderer.register('swig', 'html', njkRenderer);