html.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. var html = exports,
  2. cheerio = require('cheerio');
  3. //
  4. // Enable XSS protection of strings by default
  5. //
  6. html.safeValues = true;
  7. html.render = function (data, tpl) {
  8. //
  9. // Create the current rendering context by loading the tpl
  10. //
  11. var $ = cheerio.load(tpl);
  12. if(typeof data !== "object") {
  13. return $.html();
  14. }
  15. if (Array.isArray(data)) {
  16. //
  17. // Create a clone of the template we are going to use
  18. //
  19. var clone = $.html(),
  20. result = '';
  21. //
  22. // For every item in the array, append a filled out clone
  23. //
  24. data.forEach(function(item){
  25. result += html.render(item, clone)
  26. });
  27. return result;
  28. } else {
  29. Object.keys(data).forEach(function (prop) {
  30. var attr, og, value;
  31. og = prop;
  32. //
  33. // Determine if a period was found in property name,
  34. // if so this indicates the value should be assigned to an XML node attribute
  35. //
  36. if (prop.search('.') !== -1) {
  37. prop = prop.split('.');
  38. attr = prop[1];
  39. prop = prop[0];
  40. }
  41. //
  42. // For every property in the data object
  43. //
  44. if(typeof data[prop] === 'object') {
  45. value = html.render(data[prop], $('.' + prop).html())
  46. } else {
  47. value = stripXSS(data[og])
  48. }
  49. //
  50. // If the property value is an object, iterate again
  51. //
  52. if ($('.' + prop).length > 0) {
  53. if (attr) {
  54. $('.' + prop).attr(attr, value);
  55. } else {
  56. $('.' + prop).html(value);
  57. }
  58. }
  59. });
  60. }
  61. return $.html();
  62. };
  63. var stripXSS = html.stripXSS = function (str) {
  64. // Prase string into server-side Level 1 DOM ( XML only )
  65. var dom = cheerio.load(str);
  66. // Remove any potentially harmful XML tags
  67. dom('script').remove();
  68. dom('meta').remove();
  69. // Turn the XML document back into a string of HTML
  70. return dom.html();
  71. };