So I'm developing this web application in Django. The exact web framework doesn't matter, but the point is: We have a nice separation between code, data and the actual HTML. The further we go however, the more we find we'd like to keep on a single web page and make the interface respond to user actions via AJAX requests. Now I find myself writing all these handler functions which expect a particular input from the AJAX request and construct large parts of the page by basically concatenating strings and data. Suddenly it's 1999 again and I'm manually creating HTML strings. This can't be it?
So my question is, what's a decent pattern/framework/... to create HTML on the browser side in a systematic fashion? I'm aware there are some templating plug-ins for jQuery, before I commit to one of those however I wonder if there isn't a more fundamental approach to this problem that can't be all that rare?
What I've done before is let my server do the processing and code generation. Keeps the load off the client.
You could load partials (views) and return them, json encoded or otherwise. If you use json, make the HTML be "content" in your response object or something similar.
This way, there's no code duplication since you can use the same views. The trick becomes how to split them up.
Instead of constructing html strings, have you considered holding an array of javascript dom objects inside of javascript classes which hold your relational database data in them and then just cycling those around / building them with AJAX based on user interactions? This is how I maintain a photo gallery of nearly 500 photos (broken into sets) on one page with dynamic preloading (allowing the user to have a full size image instantly when they select it).
Also came across this 1999 feeling and settled for jQuery tmpl. It'll allow you to keep model and views separated and more time to concentrate on the business logic. You can define a template by using a script-tag of type text/x-jquery-tmpl anywhere within the documents body and use it by addressing it by its id.
来源:https://stackoverflow.com/questions/8631492/proper-way-to-construct-html-based-on-ajax-input