Handling JSON and HTML templates in jQuery
How do you handle templating HTML and JSON without locking the HTML into javascript strings?
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 - so开发者_运维知识库me 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;
}
);
};
I would definitely use the approach "Load when needed".
Build small widget that you can load with ajax that's complete with html, data and so on. Use jquery's load function.
$('#wrapper').load('/widgets/foobar/')
And have the server create all your elements you need. It will be some more loading of data for each widget. But you don't have to create them on client side. I would say the pro out weight the cons in this. Since it will be easier for the client just to add already parsed html instead of building it up in javascrtipt.
Have you tried using Distal templates that allows you to define the template as HTML.
If you want to keep the HTML template code in the HTML and out of the JavaScript then just do something like this.
Javascript:
$(document).ready(function() {
var template = $('#template-example').html();
template.interpolate({bar:"bar",blah:"vtha"});
});
HTML:
<div id="template-example" style="display:none;">
<div>Foo: {bar}</div><div>Blah: {vtha}</div>
</div>
精彩评论