Monday, July 9, 2012

Client side templating


Client side templating


I am working for some time with javascript and jQuery and in all project I found my self in need of a small script that does a simple thing:
I have a small html template like this
<span>The is a text from {source} and the author {author}</span>
and an object {'source' : 'Journal of medicine', 'author', 'John Doe'}. 
The javascript should replace the placeholders {source} and {author} with the key values from the given object. The result would be the following:
<span>The is a text from Journal of medicine and the author John Doe</span>


Because I needed this script in a couple of projects I wrote a small jQuery plugin called jquery-template.
It is simple to use:
var str = "<span>The is a text from {source} and the author {author}</span>";
$('<div>').template(str,{'source' : 'Journal of medicine', 'author', 'John Doe'}).apendTo('body');
The above code will process the string, will replace the content of the div and it will appended it to the body.
Other examples on how to use the jquery-template can be found here.
Enjoy using it.

No comments:

Post a Comment