Very Tiny Javascript/jQuery Templating

I was in need of very simple templating capabilities in Javascript, and with the smallest library I found weighing in at 500 lines found myself compelled to write a solution. Here it is:


function render(text, data) {
	pieces = text.split(/\{(\w+)\}/)
	for (var i=0; i < pieces.length; i++ ) {
		if (i%2 == 1) {
			pieces[i] = data[pieces[i]];
		}
	}
	return pieces.join('');
}

It simply looks for variables in curly brackets and replaces them with values from a dictionary (or associative array).

I was going to add looping capabilities, but found I was ok doing the looping in javascript - that is, instead of having the loop in the html template, I'd create small html snippets that I would render in via a javascript loop and insert into the document.

Sample usage:

html:


<p id="something">Hello {name}, I wish you would {verb}.</p>

javscript:


render($('#something').html(), {name: 'Joe', verb: 'disappear' } );

So to replace the text with the rendered version:


$('#something').html( render($('#something').html(), {name: 'Joe', verb: 'disappear' } ) );

Leave a Reply