doU.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. // doU.js
  2. // (c) 2011, Laura Doktorova
  3. // https://github.com/olado/doT
  4. //
  5. // doU is an extraction and slight modification of an excellent
  6. // templating function from jQote2.js (jQuery plugin) by aefxx
  7. // (http://aefxx.com/jquery-plugins/jqote2/).
  8. //
  9. // Modifications:
  10. // 1. nodejs support
  11. // 2. allow for custom template markers
  12. // 3. only allow direct invocation of the compiled function
  13. //
  14. // Licensed under the MIT license.
  15. (function() {
  16. var doU = { version : '0.1.2' };
  17. if (typeof module !== 'undefined' && module.exports) {
  18. module.exports = doU;
  19. } else {
  20. this.doU = doU;
  21. }
  22. doU.templateSettings = {
  23. begin : '{{',
  24. end : '}}',
  25. varname : 'it'
  26. };
  27. doU.template = function(tmpl, conf) {
  28. conf = conf || doU.templateSettings;
  29. var str = '', tb = conf.begin, te = conf.end, m, l,
  30. arr = tmpl.replace(/\s*<!\[CDATA\[\s*|\s*\]\]>\s*|[\r\n\t]|(\/\*[\s\S]*?\*\/)/g, '')
  31. .split(tb).join(te +'\x1b')
  32. .split(te);
  33. for (m=0,l=arr.length; m < l; m++) {
  34. str += arr[m].charAt(0) !== '\x1b' ?
  35. "out+='" + arr[m].replace(/(\\|["'])/g, '\\$1') + "'" : (arr[m].charAt(1) === '=' ?
  36. ';out+=(' + arr[m].substr(2) + ');' : (arr[m].charAt(1) === '!' ?
  37. ';out+=(' + arr[m].substr(2) + ").toString().replace(/&(?!\\w+;)/g, '&#38;').split('<').join('&#60;').split('>').join('&#62;').split('" + '"' + "').join('&#34;').split(" + '"' + "'" + '"' + ").join('&#39;').split('/').join('&#x2F;');" : ';' + arr[m].substr(1)));
  38. }
  39. str = ('var out="";'+str+';return out;')
  40. .split("out+='';").join('')
  41. .split('var out="";out+=').join('var out=');
  42. try {
  43. return new Function(conf.varname, str);
  44. } catch (e) {
  45. if (typeof console !== 'undefined') console.log("Could not create a template function: " + str);
  46. throw e;
  47. }
  48. };
  49. }());