views:

179

answers:

2

I am writing an application that renders a list of "Job" objects from an AJAX JSON response.

What is the best way to Render the markup from the returned data. Now I'm pretty convinced that its a bad idea to generate HTML markup on the server side and return that from the AJAX call. From experience it makes the HTML hard to maintain and re factoring the content is a nightmare, so I am returning a collection of Job objects as JSON.

The question, then, is how to render the HTML based on user input? I've seen some examples of having your markup template on the page then use JQuery to clone it and populate with the relevant data the insert it into the DOM.

The problem with this is that the template contains visible content (images and suchlike) and the application needs to degrade, so I have a repeater on the page that the severside code and populate on page load if JS is not available.

Any advice would be appreciated.

+1  A: 

Depending on the complexity of your data, it might be feasible to build the HTML using jQuery objects. This still looks quite pretty and is more maintainable than just writing raw HTML:

$.ajax({
    url: 'foo',
    dataType: 'json',
    success: function(data) {



        var container = $('<div />')
                        .attr('id', 'container');

        for(var i in data.items) {
            var child = $('<div />')
                        .addClass('container-child');

            var title = $('<p />')
                        .html(data.items[i].title)
                        .addClass('item-title');

            var description = $('<p />')
                              .html(data.items[i].description)
                              .addClass('item-description');

            child.append(title).append(description);

            container.append(child);
        }

        // Remove existing container
        $('div#container').remove();
        // And replace it with the just created one
        $('body').append(container);
    }
});

This method is as fast as using a 'dummy' HTML element, cloning that and populating the child elements with correct values. In my opinion, this is cleaner and easier to understand.

Tatu Ulmanen
Hmmm, I do prefer that to writing the markup server side but I would still argue its not very maintainable, particularly if our frontend developer just wants to make a quick amendment. I do agree however it should be pretty fast. I guess there is no "perfect" way of doing it without moving to MVC framework.
Sheff
+3  A: 

John Resig (the jQuery dude) did a super simple template engine that you can use clientside, Rick Strahl has a good post about it.

Trimpath have an awesome clientside templating solution called Javascript Templates - not the most imaginitive of names, but it's really quite good.

I don't normally do google links, but asp.net ajax (4.0?) has some client side templating coming out that'll let you take the JSON objects and databind them straight in.

Failing that, I'm going to be devils advocate and say "what's wrong with semantic HTML"?. As long as it's semantic, and has classes rather than hardcoded styles, I personally see nothing wrong with returning HTML from your serverside call. Sure, it's not as pure as other solutions, but it's a darn site easier to put together. In some cases I've even found that it's easier to maintain as you let the "serverside coder" return HTML with embedded classes and the "clientside coder" can style that up 6 ways to sunday :-)

Dan F
+1 for the Template engine links, I think that's exactly what I'm looking for. I disagree about returning html from JS methods however. I guess its partly being a 3 tier purist, but also its just boxes you into a corner if any changes are required in the frontend, the server code needs re factoring and also it's hard to read and maintain HTML that's constructed using whatever string manipulation methods are used to build the markup. Even the best Stringbuilder / string.Format techniques cause frontend developers some headaches.
Sheff
+1 You beat me to it. I'm using Resig's micro-template for a while and it's really bumped up my productivity.
David Robbins
No worries, I hear you loud and clear about the html from JS methods. It just feels dirty most of the time, in all but the most semantic of places :-)
Dan F
Thanks Dan the John Resig’s Microtemplating engine worked a treat for me, just what I wanted, It allowed me to abstract away the markup in an easy to maintain format which is never rendered. Would recommend to anyone.
Sheff