![]() | This article includes alist of references,related reading, orexternal links,but its sources remain unclear because it lacksinline citations. Please helpimprove this article byintroducing more precise citations.(July 2013) (Learn how and when to remove this message) |
JavaScript templating refers to theclient sidedata binding method implemented with theJavaScript language. This approach became popular thanks to JavaScript's increased use, its increase in client processing capabilities, and the trend to outsource computations to the client's web browser. Popular JavaScript templating libraries areAngularJS,Backbone.js,Ember.js,Handlebars.js,JSX (used byReact),Vue.js andMustache.js. A frequent practice is to use doublecurly brackets (i.e. {{key}}) to call values of the given key from data files, oftenJSON objects.
All examples use an external filepresidents.json
with following contents
{"presidents":[{"name":"Washington","firstname":"George","born":"1732","death":"1799"},{"name":"Lincoln","firstname":"Abraham","born":"1809","death":"1865"}]}
All examples will produce the following HTMLlist:
Library | HTML Code | Explanation |
---|---|---|
<linkrel="stylesheet"type="text/css"href=".../template.css"/><scriptsrc=".../jquery.min.js"></script><scriptsrc=".../jquery.template.min.js"></script> ➊Our favorite presidents are:<ulid="target"><litemplate="[presidents]"z-var="name ., born ., death ."> ${name} (${born}-${death})</li></ul> ➋<script>$.getJSON('.../presidents.json',function(data){$('#target').template(data);});</script> ➌ | ➊ Load the necessary resources, including requiredjQuery | |
<scriptsrc=".../jquery.min.js"></script><scriptsrc=".../mustache.min.js"></script> ➊Our favorite presidents are:<ulid="target"></ul> ➋<scriptid="president-template"type="text/template">{{#presidents}}<li>{{name}}({{born}}-{{death}})</li>{{/presidents}}</script> ➌<script>$.getJSON('.../presidents.json',function(data){vartemplate=$('#president-template').html();varinfo=Mustache.to_html(template,data);$('#target').html(info);});</script> ➍ | ➊ Load the necessary libraries, heremustache.js andjQuery |
Templating becomes useful when the information distributed may change, is too large to be maintained in various HTML pages by available human resources and not large enough to require heavier server-side templating.