Jump to content

JavaScript templating

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Yug (talk | contribs) at 18:04, 31 March 2013 (Created page with ''''Javascript templating''' refers to client side data binding method implemented with Javascript language. This approach became popular t...'). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
(diff) ← Previous revision | Latest revision (diff) | Newer revision → (diff)

Javascript templating refers to client side data binding method implemented with Javascript language. This approach became popular thanks to Javascript increase use, increase in client processing capabilities, and the trend to outsource calculus to the client's web browser. Popular Javascript templating librairies being Angular.js, Backbone.js, Ember.js, Handlebar.js, Mustache.js. A frequent practice is to use double [bracket]s "{{key}} to call values of the given key from data files, often JSON objects.

Example

With the data collected within, by example, a JSON file "presidents.json" such :

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

The HTML code providing an "anchor" :

<body>
	<ul id="anchor"></ul>
</body>

The Javascript load the needed libraries, here mustache.js and Jquery, provide a template named "president-template", and a function grasping the json data, and for each people's subitem, filling one template and appending it to the html page's anchor.

	<script src="http://cdnjs.cloudflare.com/ajax/libs/mustache.js/0.7.0/mustache.min.js"></script>
	<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

	<script id="president-template" type="text/template">
		{{#people}}
			<li>{{name}} ({{born}}-{{death}})</li>
		{{/people}}
	</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>

See also