Jump to content

JavaScript templating

From Wikipedia, the free encyclopedia

This is an old revision of this page, as edited by Narohi (talk | contribs) at 18:28, 19 October 2013. The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

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 calculus to the client's web browser. Popular Javascript templating libraries are Angular.js, Backbone.js, Ember.js, Handlebars.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

  • JavaScript templates, Mozilla Developer Network, 2013
  • Basavaraj, veena (2012), The client-side templating throwdown: mustache, handlebars, dust.js, and more, Linkedin.com
  • Villalobos, Ray (2012), Introduction to JavaScript Templating (video tutorial) with Mustache.js, ViewSource.com
  • Burgess, Andrew (2012), Best Practices When Working With JavaScript Templates, Net.tutsplus.com
  • Landau, Brian (2009), Benchmarking Javascript Templating Libraries
  • http://www.jquery4u.com/javascript/10-javascript-jquery-templates-engines/