Handling JSON and HTML templates in jQuery
- by Toby Hede
I have an ajax-enabled site that presents a lot of dynamic content by interpolating JSON values with HTML. This all works fine.
BUT it means I have significant amounts of HTML all through my JavaScript.
For example:
var template = "<div>Foo: {bar}</div><div>Blah: {vtha}</div>";
template.interpolate({bar:"bar",blah:"vtha"});
I have cut this down a fair bit - some of my dynamic elements have quite a lot of HTML and a lot going on.
I am using jQuery and I am building on Rails, so if there is something smart in either framework, that would be great.
For reference, the String interpolation function used above is:
String.prototype.interpolate = function (o) {
return this.replace(/{([^{}]*)}/g,
function (a, b) {
var r = o[b];
return typeof r === 'string' || typeof r === 'number' ? r : a;
}
);
};