I’m developing a web site. On the server-side I’m using python (and Genshi) to manipulate/generate the HTML. But I find myself manipulating the same kind of HTML fragments on the client-side, using Javascript.
Let me show you an example. Suppose I have an editable list of items:
<form .... >
<ul>
<li id="i1">Name: <input type="text" name="i1" value="Item 1" /> <a href="#">[del]</a></li>
<li id="i2">Name: <input type="text" name="i2" value="Item 2" /> <a href="#">[del]</a></li>
</ul>
<a id="addnew" href="#">[new]</a>
</form>
Note: The [new] anchor dynamically adds new items to the form. It doesn’t (have to) make any request to the server.
Both the server and the client have to know this “template” (pseudo-code):
<li id="${id}">Name: <input type="text" name="${name}" value="${val} " /> <a href="#">[del]</a></li>
The server has to know it to create the initial HTML list, and the client has to know it to allow the users to add and remove items, using the anchors.
What would you say are the best-practices to improve reuse in a scenario like this?
Some approaches that I already know I’d like to avoid:
- Creating the initial list using javascript. I’m trying to use javascript to improve some parts of the user interaction only
- Using a template language that I can somehow reuse between the client and the server is not an option because I’m stuck with Genshi for now
- Generating Javascript on the server side. Tried this before, and it’s a pain to debug, due to the extra level of indirection
How about store the HTML in a hidden div with some initial placeholders, use JavaScript to copy that into the visible piece of the UI and replace the place holders with your AJAX response. The response could be JSON (Key/Value pair list).