I'm writing a facebook-like posting system where a user can type in a text comment and have it immediately appear on the page in a properly styled and formatted box, as simultaneously the text is ajax'd to the backend to be stored. A comment is fundamentally a HTML5 , but there's a fairly complicated level of structure to it, so the actual text should appear in a div within a div within a div ultimately within the article. I'm doing this DOM manipulation with jquery.
When the page is generated, the backend needs to iterate over every comment, and insert the comment text (as well as metadata like name of poster, timestamp, etc.) into the appropriate places in a django template.
This presents a conceptual problem - I'm now duplicating a fairly complicated set of nested html tags with appropriate class and id names in two places in my code: the js file with the jquery to add a new comment, and the backend templating engine to generate the initial page html. This is already a problem for me because I'm still in the process of designing exactly what needs to happen style-wise in a comment and having this complicated bundle of HTML in two places in my code has already tripped me up.
What is the best practice for dealing with this sort of HTML duplication? I can't remove the jquery, because I need that to handle the dynamic addition of comments. At the same time, it seems wasteful to give up the power of django's templating engine to build the HTML structure I need once and fill in the details on a per-comment basis - plus I don't want to always render a blank page and build up possibly very many comments dynamically with jquery DOM manipulation every time the user loads a page. Is there something I'm not thinking of that would solve this problem?
Just get your Ajax handling views to return rendered HTML fragments, using the templates, rather than JSON, and the jQuery simply inserts them in the right place, rather than building them up from raw data.