octemplate.js 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  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. for (var key = 0; key < this.vars.length; key++) {
  62. if(typeof this.vars[key] === 'string') {
  63. this.vars[key] = self.options.escapeFunction(this.vars[key]);
  64. }
  65. }
  66. }
  67. var _html = this._build(this.vars);
  68. return $(_html);
  69. },
  70. // From stackoverflow.com/questions/1408289/best-way-to-do-variable-interpolation-in-javascript
  71. _build: function(o){
  72. var data = this.elem.attr('type') === 'text/template' ? this.elem.html() : outerHTML(this.elem.get(0));
  73. try {
  74. return data.replace(/{([^{}]*)}/g,
  75. function (a, b) {
  76. var r = o[b];
  77. return typeof r === 'string' || typeof r === 'number' ? r : a;
  78. }
  79. );
  80. } catch(e) {
  81. console.error(e, 'data:', data)
  82. }
  83. },
  84. options: {
  85. escapeFunction: function(str) {return $('<i></i>').text(str).html();}
  86. }
  87. };
  88. $.fn.octemplate = function(vars, options) {
  89. var vars = vars ? vars : {};
  90. if(this.length) {
  91. var _template = Object.create(Template);
  92. return _template.init(vars, options, this);
  93. }
  94. };
  95. })( jQuery );