Handling JSON and HTML templates in jQuery
Posted
by Toby Hede
on Stack Overflow
See other posts from Stack Overflow
or by Toby Hede
Published on 2010-04-19T13:53:02Z
Indexed on
2010/04/19
14:03 UTC
Read the original article
Hit count: 214
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;
}
);
};
© Stack Overflow or respective owner