Reputation: 6115
I'm currently creating a "facebook-like" news feed, and I'm wondering if I'm better off having 1.) anelement within my HTML which I clone in my javascript and append the data I get from my ajax call to in the right places, or 2.) if it would be better to generate the whole element inside the javascript.
In terms of best practices, what is more generally acceptable and allow me the best extensibility?
Is it possibly a situation based answer, or is there a clear answer in this case I should stick to across my site?
A con to option 2 I see is that its generally not a good idea to be writing HTML in your javascript.
A con to option 1 might be if I try to start manipulating the overall structure of the status so its different on different pages, its going to be hard to keep track and I could mess up things overall.
Upvotes: 2
Views: 209
Reputation: 1113
Basically, you need to generate HTML from JavaScript in cases you have to create interfaces that differ depending on the configuration e.g. you need to build custom dynamic forms as a input projection of a composite model.
In simple cases like yours HTML is cool. But you may take a look at jQuery Template plugin or something similar for your template (if you are using one).
What I usually do when I have to create just one template, I echo it to the JavaScript with some json_encode analog, and put there some variables like {{name}}, {{date}} etc. In JavaScript I just do a replace function, but is kinda fast and dirty.
Upvotes: 0
Reputation: 1075765
I think the answer varies quite a lot on the situation. It varies on the size and complexity of the template, etc. I tend prefer to use HTML templates from my HTML page (so I can use my authoring tools and such) and clone them. I'm careful to avoid tying the JavaScript code to the specific structure of the HTML (instead preferring class names, name
attributes, and/or data-xyz
attributes as markers for where things go). That lets you change the HTML (and use different HTML on different pages, with the same data) without worrying about blowing up your JavaScript code. Just make sure the markers are there (or not, if you want to leave some information off on a particular page.)
I'll add a third option to your two:
3) Have the ajax return an HTML fragment that you simply append to the page.
This last is most useful if you're already using some templating technology on the server-side to generate the initial parts of your feed, because then you can have the code in one place rather than two.
Upvotes: 4