octemplate.js 3.0 KB

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