cheerio.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. 'use strict';
  2. /**
  3. * Module dependencies.
  4. */
  5. var cheerio = require('cheerio');
  6. var utils = require('./utils');
  7. var cheerioLoad = function(html, options, encodeEntities) {
  8. options = Object.assign({decodeEntities: false, _useHtmlParser2:true}, options);
  9. html = encodeEntities(html);
  10. return cheerio.load(html, options);
  11. };
  12. var createEntityConverters = function () {
  13. var codeBlockLookup = [];
  14. var encodeCodeBlocks = function(html) {
  15. var blocks = module.exports.codeBlocks;
  16. Object.keys(blocks).forEach(function(key) {
  17. var re = new RegExp(blocks[key].start + '([\\S\\s]*?)' + blocks[key].end, 'g');
  18. html = html.replace(re, function(match, subMatch) {
  19. codeBlockLookup.push(match);
  20. return 'JUICE_CODE_BLOCK_' + (codeBlockLookup.length - 1) + '_';
  21. });
  22. });
  23. return html;
  24. };
  25. var decodeCodeBlocks = function(html) {
  26. for(var index = 0; index < codeBlockLookup.length; index++) {
  27. var re = new RegExp('JUICE_CODE_BLOCK_' + index + '_(="")?', 'gi');
  28. html = html.replace(re, function() {
  29. return codeBlockLookup[index];
  30. });
  31. }
  32. return html;
  33. };
  34. return {
  35. encodeEntities: encodeCodeBlocks,
  36. decodeEntities: decodeCodeBlocks,
  37. };
  38. };
  39. /**
  40. * Parses the input, calls the callback on the parsed DOM, and generates the output
  41. *
  42. * @param {String} html input html to be processed
  43. * @param {Object} options for the parser
  44. * @param {Function} callback to be invoked on the DOM
  45. * @param {Array} callbackExtraArguments to be passed to the callback
  46. * @return {String} resulting html
  47. */
  48. module.exports = function(html, options, callback, callbackExtraArguments) {
  49. var entityConverters = createEntityConverters();
  50. var $ = cheerioLoad(html, options, entityConverters.encodeEntities);
  51. var args = [ $ ];
  52. args.push.apply(args, callbackExtraArguments);
  53. var doc = callback.apply(undefined, args) || $;
  54. if (options && options.xmlMode) {
  55. return entityConverters.decodeEntities(doc.xml());
  56. }
  57. return entityConverters.decodeEntities(doc.html());
  58. };
  59. module.exports.codeBlocks = {
  60. EJS: { start: '<%', end: '%>' },
  61. HBS: { start: '{{', end: '}}' }
  62. };