Template troubles
So recently I’ve come across a lingering dilemma in my web development practice. I want to be able to render JSON objects fetched from my server as HTML for dynamic insertion on the client side, but I don’t want to have to totally rewrite my native PHP templates in JS. So I wind up writing shit like this…
$(this).find('input.submit').click(function(){ $.post('/edges.json', form.serialize(), function(data, textstatus){ if(textstatus=="success"){ // <lotsa-crap> var edge = data.edge; var source_link = $("<a/>").attr('href', "/"+edge.source).html(edge.source); var target_link = $("<a/>").attr('href', "/"+edge.target).html(edge.target); var delete_link = $("<a/>").addClass('edge_delete') .attr('href', "#edge_delete-"+edge.id).html(' '); $("<li/>").attr('id', "edge_"+edge.id) .append(source_link).append(target_link) .append(' ').append(delete_link) .insertAfter("ul.edges li:last"); // </lotsa-crap> div.find('input[name=edge[target]]').val('').focus(); } }, "json"); return false; });
What a pain in the ass. I don’t want to have to rebuild every template in the DOM. I’d rather just …
$(this).find('input.submit').click(function(){ $.post('/edges.json', form.serialize(), function(data, textstatus){ if(textstatus=="success"){ // <less-crap> $.htmlFromTemplate('edge_li', data.edge).insertAfter("ul.edges li:last"); // </less-crap> div.find('input[name=edge[target]]').val('').focus(); } }, "json"); return false; });
But my templates are written in PHP and fractured into partials …
<ul class="edges"> <?php foreach($edgeSet as $edge) { ?> <li id="edge_<?=$edge->id?>"> <?php Partial::draw('details', $edge) ?> <a href="#edge_delete-<?=$edge->id?>" class="edge_delete"> </a> </li> <?php } ?> </ul>
So now I’m getting fed up and considering ditching PHP template rendering altogether. Just serving HTML templates and letting Javascript hydrate them with JSON from my application’s web service in the browser. Any request to the site with header Accept: text/html will be responded to with a static bootstrap HTML file. From that point on, the application flow is in the hands of Javascript. Feels a lot like a Facebook app. In fact, it will likely make it much easier to port features to a Facebook app when the time comes.
I still want Google to index my data, so I’ll probably serve HTTP_USER_AGENT .*(yahoo|googlebot).* some bare scaffolding representation of the site’s resources for indexing.
But you know, I just can’t help feel that this could all be avoided if I had some intermediary template language that could be compiled into both PHP and JS.
Or some (fast) PHP library similar to hpricot / hquery.
Or a (fast) way to run server-side javascript.
In the end, I get the feeling that offloading the site’s template rendering to the client is going to save my server a hell of a lot in view-rendering CPU cycles and excessive markup trafficking.
Have I overlooked some sort of Silver Bullet that I should know about?
Comments(0)