JST - JavaScript Templates

JST - A client-side template processor

Randy Morey, 27 Jun 2008

As AJAX and JavaScript-powered applications become more complex, the need for client-side templating becomes more apparent. JavaScript Templates (or JST for short) provides a powerful, familiar syntax. JST is similar to velocity and Smarty.

Without going into too much detail, I want to demonstrate the separation of templates and contexts within the JST system. A template is the unrendered document fragment. A template is parsed up front into a more efficient representation: a JavaScript function. That function accepts a context and outputs rendered content. A context is simply a JavaScript object. Because of this separation, a single template may be rendered any number of times using different contexts. And since templates are parsed up front, subsequent calls to render them are fast.


A Simple Template Example

The Template

The Context


	context = {
		templateName: 'Super Awesome Template',
		benefits: [
			'provides a familiar templating syntax',
			'separates functional code from content',
			'makes your code clean and easy to read'
		]
	};