Let’s dive into an example of javascript using HTML templates that you can re-use on the website/app.
Javascript Templates
is a 1KB lightweight, fast & powerful JavaScript templating engine with zero dependencies by © Sebastian Tschan
Compatible with server-side environments like Node.js, module loaders like RequireJS or webpack and all web browsers.
This is how to embed HTML templates using Javascript Templates
1 2 3 4 5 6 7 8 9 |
<script src="<SOURCE_FOLDER>/tmpl.min.js"></script> <script type="text/x-tmpl" id="tmpl-loader"> <div class="loader pagewidth"><div class="bouncywrap"> <div class="dotcon dc1"><div class="dot"></div></div> <div class="dotcon dc2"><div class="dot"></div></div> <div class="dotcon dc3"><div class="dot"></div></div> </div></div> </script> |
Then create the object using the template.
1 |
var result = tmpl('tmpl-loader'); |
Then, you can insert it at the beginning of the <body>
element like this…
1 2 |
document.body.insertAdjacentHTML('afterBegin',result()); // prints to beginning of <body> result(); // returns '<div class="loader pagewidth">...</div>' |
Backbone JS
Backbone.js gives structure to web applications by providing models with key-value binding and custom events, collections with a rich API of enumerable functions, views with declarative event handling, and connects it all to your existing API over a RESTful JSON interface. https://backbonejs.org
To do this using Backbonejs framework.
1 2 3 4 5 6 7 8 9 10 |
<script src="<SOURCE_FOLDER>/underscore.min.js"></script> <script src="<SOURCE_FOLDER>/backbone.min.js"></script> <script type="text/template" id="tmpl-loader"> <div class="bouncywrap" data-name="<%= name %>" data-color="<%= color %>" data-sound="<%= sound %>"> <div class="dotcon dc1"><div class="dot"></div></div> <div class="dotcon dc2"><div class="dot"></div></div> <div class="dotcon dc3"><div class="dot"></div></div> </div> </script> |
Then create the object using the template.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
var result = Backbone.View.extend({ tagName: 'div', // defaults to div if not specified className: 'loader pagewidth', // optional events: { 'click': 'alertTest', 'click .edit': 'editAnimal', 'click .delete': 'deleteAnimal' }, newTemplate: _.template(document.getElementById('tmpl-loader').innerHTML), // external template initialize: function() { this.render(); }, render: function() { this.$el.html(this.newTemplate(this.model)); // calls the template } }); var App = new result({model:{name: 'Mike', color: "blue",sound: 'buzz'}}); |
Then, you can insert it at the beginning of the <body>
element like this…
1 2 |
document.body.insertAdjacentHTML('afterBegin',App.el.outerHTML); // prints to beginning of <body> App.el.outerHTML; // returns <div class="loader pagewidth"><div class="bouncywrap" data-name="Mike" data-color="blue" data-sound="buzz">...</div></div> |
Last Updated: August 21, 2023(Share)