Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using an HTML snippet for a template in JavaScript (jQuery)

I currently am working on a little app that requests user info from my server and displays them using a special template.

At first, I just hardcoded the little snippet in jQuery:

 $("<li><div class='outer'><table><tr><td rowspan=2 class='imgcontainer'><img class='thumb'/></td><td><span class='username'/></td></tr><tr><td><span class='name'/></td></tr></table></div></li>")

I clone it several times.

It's ugly and I want it to have syntax highlighting and whatnot, so it would be better for me to have it in the HTML file itself.

Also, it will make merges easier so somebody can just change a line or two.

Is there a pattern for this? Am I OK putting it in the HTML file that I include this JS in (there's only one), and making it hidden using CSS.

The third option I thought of is just creating a separate HTML file and having jQuery request that from the server to keep it separate. Is this technique used much?

Also, is there any term I can use to describe what I'm doing? (It's harder to ask a question for a concept I don't know the name for)

like image 951
mikelikespie Avatar asked Apr 20 '09 02:04

mikelikespie


People also ask

How do I load a JavaScript template?

Use jQuery and the . load() ( http://api.jquery.com/load/ ) method to inject the loaded document into the DOM.

How do I get HTML templates?

You can use the <template> tag if you have some HTML code you want to use over and over again, but not until you ask for it. To do this without the <template> tag, you have to create the HTML code with JavaScript to prevent the browser from rendering the code.

What is HTML snippet?

An HTML snippet is a small portion of source code in HTML. They can be used to build different elements (like a list view, different styled buttons, text display, customized search bar and so on).


1 Answers

I gave a similar answer on SO earlier today. What you are looking for is called micro-templates. John Resig posted this on his blog. Essentially you can get a json dataset and apply a template to the data to create html and update the DOM.

like image 129
David Robbins Avatar answered Oct 07 '22 02:10

David Robbins