You've said you're using Prototype. You could make use of its Template class. You could even store templates on the server and demand-load them via ajax if you like (although I'd worry about the number of HTTP requests), in order to keep your code and your markup completely distinct.
For instance, here's a Prototype template for building a table row:
<tr><td>#{name}</td><td>#{description}</td></tr>
You have various options for where and how to store the template text:
- You can put it in its own file you demand-load via Ajax, although if there are a lot of them it could start being excessive HTTP requests.
- You can put them in your JavaScript, but then you've tied your markup to your JavaScript and I get the impression you don't want to do that.
- You can include them in your main page with
display: none, extract them as HTML, and then reuse them.
In all three of those cases, eventually you end up with a string containing the template text, e.g.:
var rowString = "<tr><td>#{name}</td><td>#{description}</td></tr>";
(But again, you may not need to put it actually in the JavaScript.)
From the string, you make a template:
var rowTemplate = new Template(rowString);
And then use it:
$('tableBodyId').insert({
bottom: rowTemplate.evaluate({
name: bizobject.name.escapeHTML(),
description: bizobject.description.escapeHTML()
})
});
Note that (sadly) you do have to do the HTML escaping yourself (because Prototype's templates aren't specifically tied to HTML, you can use them for any situation where you have a templated string). Or you can make a fairly small change to the Template class to do it for you (that's what I did, when I was using Prototype; I actually made it possible to call functions on template items).
innerHTMLto append it. This is bad in most cases. Or use the DOM API to create the elements which is perfectly fine to do so. Of course it will still be tedious for complex elements.