JavaScript templating

JavaScript templating refers to the client side data binding method implemented with the JavaScript 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 are AngularJS, Backbone.js, Ember.js, Handlebars.js, Vue.js and Mustache.js. A frequent practice is to use double curly brackets (i.e. {{key}}) to call values of the given key from data files, often JSON objects.

Example

Explanation Result

The data is collected within, for example, an external JSON file "presidents.json" such as :

"presidents" : [
    { "name": "Washington", "firstname": "George", "born": "1732", "death": "1799" },
    { "name": "Lincoln", "firstname": "Abraham", "born": "1809", "death": "1865" },
    ...
]

The HTML code provides an "anchor" :

<body>
	Our favorite presidents are:
	<ul id="anchor"></ul>
</body>

The JavaScript is in several important parts.
➊ Load the necessary libraries, here mustache.js and jQuery
➋ provide a template named "president-template".
➌ Last is a function grasping the JSON data, and for each president's subitem, grasping one template and filling it to finally select the HTML page's anchor appending the whole to it.

<script src="js/mustache.min.js"></script>  // 
<script src="js/jquery.min.js"></script>

<script id="president-template" type="text/template">  // ➋
	{{#presidents}}
		<li>{{name}} ({{born}}-{{death}})</li>
	{{/presidents}}
</script>

<script> // ➌
	$(function() {
		$.getJSON('http://.../presidents.json', function(data) {
		    var template = $('#president-template').html();
		    var info = Mustache.to_html(template, data);
		    $('#anchor').html(info);
		});
	});
</script>

Our favorite presidents are:

  • Washington (1732-1799)
  • Lincoln (1809-1865)

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.

See also

References

This article is issued from Wikipedia. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.