Mailing List



NerdyHearn - Blog

<< Back To All Blogs

Implementing a Templating system in Javascript

Friday, March 28th, 2008

A templating system can be very useful in javascript. Using a templating system can mean that your designers can setup basic layout in HTML only and the developer of the javascript can implement more advanced javascript as necessary, as well as doing value-substitution. This basic templating system can substitute variables and have a template stored in either a textarea (recommended), input, span or div. It could easily be expanded to create your own internal scripting system for iterating variables, implementing basic if-then-else logic, and many more concepts.

The code for the class would be as follows:

NerdyHearn.Com.Template = function(id, theObject) {
this.obj = theObject; = id;
this.text = document.getElementById(id).value;

// Adding this to check for innerHTML if the template is loaded from a DIV or SPAN instead of TEXTAREA or INPUT
if (this.text==null || this.text.empty()) {
this.text = document.getElementById(id).innerHTML;


if (!NerdyHearn.Com.Template.prototype.matchVariables) {
NerdyHearn.Com.Template.prototype.matchVariables = function() {
// Match any variables such as $tom, $tom123, etc
var matches = this.text.match(/$[a-zA-z0-9]*/gi);

if (matches != null) {
for (var a=0; a matches[a] = matches[a].substring(1, matches[a].length);
var varname = 'this.obj.' + matches[a];
var replacewith = eval(varname);
this.text = this.text.replace("$" + matches[a],replacewith);

To use this templating system you would do as follows:

The template itself, implemented using a textarea:
<textarea id="mytemplate" class="hidden">
<div id="$id">

Create the object to hold variables:
var myobj; = "12345";
myobj.Name = "NerdyHearn Template Test";
myobj.Description = "An example templating system";

var mytemplate = new NerdyHearn.Com.Template("mytemplate", myobj);

Once the class is instantiated you can access the templated text by doing the following:


If you wanted to replace a div with the templated text you could do as follows:

document.getElementById('IdToReplace').value = mytemplate.text;

This is a quick-and-dirty implementation of a templating system for javascript, but can be very powerful for many different uses.

Templating Tom Out.


Currently no comments.

Add A Comment



Email Address: (not public, used to send notifications on further comments)


Enter the text above, except for the 1st and last character:

NerdyHearn - Latest tech news relating to C#, ASP.NET, SharePoint, PHP, general development, and more. SaveMySerials - Protect yourself from theft, fire, natural disasters and more by recording your serial numbers