Over a million developers have joined DZone.

Easy HTML Templating with jQuery

· Web Dev Zone

Start coding today to experience the powerful engine that drives data application’s development, brought to you in partnership with Qlik.

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|” />
</li>
</script>

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!

 

Create data driven applications in Qlik’s free and easy to use coding environment, brought to you in partnership with Qlik.

Topics:

Published at DZone with permission of Sara Chipps, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

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

{{ parent.tldr }}

{{ parent.urlSource.name }}