views:

107

answers:

2

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 - 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;
        }
    );
};
A: 

Are you searching for something like this : http://www.infoq.com/news/2010/04/Microsoft-jQuery ?

Jarek
A: 

I would defiantly 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.

fredrik