octemplate.js 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. /**
  2. * jQuery plugin for micro templates
  3. *
  4. * Strings are automatically escaped, but that can be disabled by setting
  5. * escapeFunction to null.
  6. *
  7. * Usage examples:
  8. *
  9. * var htmlStr = '<p>Bake, uncovered, until the {greasystuff} is melted and the {pasta} is heated through, about {min} minutes.</p>'
  10. * $(htmlStr).octemplate({greasystuff: 'cheese', pasta: 'macaroni', min: 10});
  11. *
  12. * var htmlStr = '<p>Welcome back {user}</p>';
  13. * $(htmlStr).octemplate({user: 'John Q. Public'}, {escapeFunction: null});
  14. *
  15. * Be aware that the target string must be wrapped in an HTML element for the
  16. * plugin to work. The following won't work:
  17. *
  18. * var textStr = 'Welcome back {user}';
  19. * $(textStr).octemplate({user: 'John Q. Public'});
  20. *
  21. * For anything larger than one-liners, you can use a simple $.get() ajax
  22. * request to get the template, or you can embed them it the page using the
  23. * text/template type:
  24. *
  25. * <script id="contactListItemTemplate" type="text/template">
  26. * <tr class="contact" data-id="{id}">
  27. * <td class="name">
  28. * <input type="checkbox" name="id" value="{id}" /><span class="nametext">{name}</span>
  29. * </td>
  30. * <td class="email">
  31. * <a href="mailto:{email}">{email}</a>
  32. * </td>
  33. * <td class="phone">{phone}</td>
  34. * </tr>
  35. * </script>
  36. *
  37. * var $tmpl = $('#contactListItemTemplate');
  38. * var contacts = // fetched in some ajax call
  39. *
  40. * $.each(contacts, function(idx, contact) {
  41. * $contactList.append(
  42. * $tmpl.octemplate({
  43. * id: contact.getId(),
  44. * name: contact.getDisplayName(),
  45. * email: contact.getPreferredEmail(),
  46. * phone: contact.getPreferredPhone(),
  47. * });
  48. * );
  49. * });
  50. */
  51. (function( $ ) {
  52. /**
  53. * Object Template
  54. * Inspired by micro templating done by e.g. underscore.js
  55. */
  56. var Template = {
  57. init: function(vars, options, elem) {
  58. // Mix in the passed in options with the default options
  59. this.vars = vars;
  60. this.options = $.extend({},this.options,options);
  61. this.elem = elem;
  62. var self = this;
  63. if(typeof this.options.escapeFunction === 'function') {
  64. var keys = Object.keys(this.vars);
  65. for (var key = 0; key < keys.length; key++) {
  66. if(typeof this.vars[keys[key]] === 'string') {
  67. this.vars[keys[key]] = self.options.escapeFunction(this.vars[keys[key]]);
  68. }
  69. }
  70. }
  71. var _html = this._build(this.vars);
  72. return $(_html);
  73. },
  74. // From stackoverflow.com/questions/1408289/best-way-to-do-variable-interpolation-in-javascript
  75. _build: function(o){
  76. var data = this.elem.attr('type') === 'text/template' ? this.elem.html() : outerHTML(this.elem.get(0));
  77. try {
  78. return data.replace(/{([^{}]*)}/g,
  79. function (a, b) {
  80. var r = o[b];
  81. return typeof r === 'string' || typeof r === 'number' ? r : a;
  82. }
  83. );
  84. } catch(e) {
  85. console.error(e, 'data:', data);
  86. }
  87. },
  88. options: {
  89. escapeFunction: escapeHTML
  90. }
  91. };
  92. $.fn.octemplate = function(vars, options) {
  93. var vars = vars ? vars : {};
  94. if(this.length) {
  95. var _template = Object.create(Template);
  96. return _template.init(vars, options, this);
  97. }
  98. };
  99. })( jQuery );