I’m seeking input on this topic, as explained below. In particular I am looking for a “best known method” or design pattern regarding how to dynamically build HTML.
This is a very common task for me:
Submit something to a server via a POST –> get a list of results back in JSON format –> take this list of 0 to n results and display them, often as a list. This usually means building the actual HTML in Javascript (jQuery) with something like:
HTMLResult = "<div id=.... "
HTMLResult = HTMLResult + JSONDataElement
HTMLResult = "</div>"
...
Then I add each element using jQuery or bundle them up and replace the HTML of some container div.
I’m sick of doing this. It’s error prone, ugly, inefficient, etc…
I’d much rather do something more OO.
Perhaps an Element would be defined somehow – is it in a div, span, what does it contain… so that I can do something like this:
tempElement = new Element
tempElement.text = JSONData.text
ResultsList.addElement(tempElement)
I am seeking any input on better ways to do what I’ve described. I prefer a minimal toolset: HTML, CSS, jQuery.
(Also what about building the HTML on the backend, in this case, Django)?
Cloning elements is supposedly quite fast, so what I sometimes do is include templates of the elements to be generated in the initial page, with
display: none. Then, when I receive data from the server, I canThen, it depends on how much must be replaced. Sometimes I just set the required attributes and set the text etc., sometimes I have placeholders in the template and go something like
where
paramObjholds the values to replace the placeholders, andsupplantis taken from Crockford. Modifying the String prototype is not without issues, of course, but can, in this case, easily be avoided by using a function.