Guest User

Untitled

a guest
Apr 21st, 2018
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.29 KB | None | 0 0
  1. /* Ejs parser for Nodejs
  2. *
  3. * Copyright (c) 2009, Howard Rauscher
  4. * Licensed under the MIT License
  5. */
  6.  
  7. // PUBLIC METHODS
  8. function parse(input) {
  9. var output = [];
  10. var innerOutput = [];
  11. var isEval = false;
  12.  
  13. output.push('(function() {\nvar output = [];');
  14. for(var i = 0, len = input.length; i < len; i++) {
  15. var chr = input[i];
  16. if(isEval) {
  17. if(chr === '%' && input[i+1] === '>') {
  18. i++;
  19. isEval = false;
  20. output.push(new EvalString(innerOutput.join('')));
  21. innerOutput = [];
  22. }
  23. else {
  24. innerOutput.push(chr);
  25. }
  26. }
  27. else {
  28. if(chr === '<' && input[i+1] === '%') {
  29. i++;
  30. isEval = true;
  31. output.push(new LiteralString(innerOutput.join('')));
  32. innerOutput = [];
  33. }
  34. else {
  35. innerOutput.push(chr);
  36. }
  37. }
  38. }
  39. if(isEval) {
  40. output.push(new EvalString(innerOutput.join('')));
  41. }
  42. else {
  43. output.push(new LiteralString(innerOutput.join('')));
  44. }
  45. innerOutput = [];
  46.  
  47. output.push('return output.join(\'\');\n})();');
  48.  
  49. return output.join('\n');
  50. }
  51.  
  52. // HELPERS
  53. function escapeString(src) {
  54. return src
  55. .replace(escapeString.ESCAPE, '\\$1')
  56. .replace(escapeString.LINE_FEED, "\\n")
  57. .replace(escapeString.CARRIAGE_RETURN, "\\r");
  58. }
  59. escapeString.ESCAPE = /(["'\\])/g;
  60. escapeString.LINE_FEED = /\n/g;
  61. escapeString.CARRIAGE_RETURN = /\r/g;
  62.  
  63. // OBJECTS
  64. function LiteralString(value) {
  65. this.value = value;
  66. }
  67. LiteralString.prototype.toString = function() {
  68. return 'output.push("'+escapeString(this.value)+'");';
  69. };
  70.  
  71. function EvalString(value) {
  72. this.value = value;
  73. this.print = (value[0] === '=');
  74. this.include_trailing_line_feed = (value[value.length - 1] !== '-');
  75.  
  76. if(this.print) {
  77. this.value = this.value.substring(1);
  78. }
  79. if(!this.include_trailing_line_feed) {
  80. this.value = this.value.substring(0, this.value.length - 1);
  81. }
  82. }
  83. EvalString.prototype.toString = function() {
  84. if(this.print) {
  85. return 'output.push('+this.value+');';
  86. }
  87. else {
  88. return this.value;
  89. }
  90.  
  91. };
  92.  
  93. exports.parse = parse;
Add Comment
Please, Sign In to add comment