Over a million developers have joined DZone.

Easy HTML Templating with jQuery

DZone's Guide to

Easy HTML Templating with jQuery

· Web Dev Zone ·
Free Resource

Access over 20 APIs and mobile SDKs, up to 250k transactions free with no credit card required

I have been wanting to write a blog about this for a while and my first post on Devlicious is the perfect place. Firstly I have to thank Jess Chadwick for his help with this when I first started out with the Bundl.it project. Working with ASP.NET MVC has been wonderous, but when I was first starting out I was confused how I would replicate some of the behavior I was used to on my heavy server controls.

I wanted my page to be quick, and to do this I wanted only the amount of HTML I need to display to be on the page. When I was using webforms I would probably do this with a repeater, but I'm using .NET MVC so I thought dynamically generating the HTML was the way to go.

Your first step is creating your template; your template is the HTML that gets added to the page. You want it to be hidden; throwing it in a script tag is a good way to do this. You need to give it an ID that can be referenced in your code. You can create multiple templates as well. I am creating an unordered list.

My template looks like this:

  <script id="ItemTemplate" type="text/html">
<li class="item" value="|rowNumber|">
<input type=”text” id=”input|rowNumber|” />

Now within my code I need to put a place holder where I want my HTML to go. I have my unordered list called url_list.

<ul id="url_list"></ul>

Now, you see that most of my items look like this “|rowNumber|” I have a variable in my code called nextUniqueItemID (I believe in extremely descriptive variable names). Here is my “addItem” function.

function addItem() {
var list = $('#url_list'), items = list.find('li');
list.append($('#ItemTemplate’).html().replace(/\|rowNumber\|/gi, nextUniqueItemID++));

The list item gets added on user action. You can interpret it how you want The first thing it does is find my unordered list using the ID selector. Then the append function locates my template using the same selector and adds it to the html inside the url_list. It also replaces the rowNumber with the nextUniqueItemID, that way when I can reference this particular input when submitting my form. It's that easy!


#1 for location developers in quality, price and choice, switch to HERE.


Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}