/index.html

https://github.com/Gazler/Underscore-Template-Loader · HTML · 92 lines · 77 code · 15 blank · 0 comment · 0 complexity · aad20ec551e6a8873425cf777be147b7 MD5 · raw file

  1. <html>
  2. <head>
  3. <script src="jquery-1.6.4.js"></script>
  4. <script src="underscore.js"></script>
  5. <script>
  6. (function() {
  7. var templateLoader = {
  8. templateVersion: "0.0.1",
  9. templates: {},
  10. loadRemoteTemplate: function(templateName, filename, callback) {
  11. if (!this.templates[templateName]) {
  12. var self = this;
  13. jQuery.get(filename, function(data) {
  14. self.addTemplate(templateName, data);
  15. self.saveLocalTemplates();
  16. callback(data);
  17. });
  18. }
  19. else {
  20. callback(this.templates[templateName]);
  21. }
  22. },
  23. addTemplate: function(templateName, data) {
  24. this.templates[templateName] = data;
  25. },
  26. localStorageAvailable: function() {
  27. try {
  28. return 'localStorage' in window && window['localStorage'] !== null;
  29. } catch (e) {
  30. return false;
  31. }
  32. },
  33. saveLocalTemplates: function() {
  34. if (this.localStorageAvailable) {
  35. localStorage.setItem("templates", JSON.stringify(this.templates));
  36. localStorage.setItem("templateVersion", this.templateVersion);
  37. }
  38. },
  39. loadLocalTemplates: function() {
  40. if (this.localStorageAvailable) {
  41. var templateVersion = localStorage.getItem("templateVersion");
  42. if (templateVersion && templateVersion == this.templateVersion) {
  43. var templates = localStorage.getItem("templates");
  44. if (templates) {
  45. templates = JSON.parse(templates);
  46. for (var x in templates) {
  47. if (!this.templates[x]) {
  48. this.addTemplate(x, templates[x]);
  49. }
  50. }
  51. }
  52. }
  53. else {
  54. localStorage.removeItem("templates");
  55. localStorage.removeItem("templateVersion");
  56. }
  57. }
  58. }
  59. };
  60. templateLoader.loadLocalTemplates();
  61. window.templateLoader = templateLoader;
  62. })();
  63. $(document).ready(function() {
  64. $('#load_remote_template').click(function() {
  65. templateLoader.loadRemoteTemplate("test_template", "templates/test_template.txt", function(data) {
  66. var compiled = _.template(data);
  67. $('#content').html(compiled({name : 'world'}));
  68. });
  69. });
  70. });
  71. </script>
  72. </head>
  73. <body>
  74. <span id="load_remote_template">Load Remote Template</span>
  75. <div id="content"></div>
  76. </body>
  77. </html>